我正在嘗試回傳一個包含屬性之一的陣列。所以有一個物件陣列,比如
[{x: 5, y: 607, width: 782, height: 602, line_width: 3, …},
{x: 10, y: 602, width: 772, height: 592, line_width: 3, …},
{x: 0, y: 400, size: 18, text: 'This cer..}, ..]
有些物件section: 'TextInstruction'定義了屬性,有些則沒有。
我正在嘗試回傳一個僅包含section沒有重復且沒有未定義的陣列。
所以return ['TextInstruction', 'RectangleInstruction', ...]
不[undefined, 'TextInstruction', 'TextInstruction', ...]
任何人都可以幫助我使用 JavaScript 來使用 reduce() 函式嗎?
uj5u.com熱心網友回復:
你不需要 reduce 來做到這一點。你可以用filter和來做map。
myArray
// filter missing sections
.filter(a => a.section)
// map to array of sections
.map(a => a.section)
// filter unique
.filter((a, i, arr) => arr.indexOf(a) === i)
uj5u.com熱心網友回復:
這樣做的reduce()方式可能是這樣的:
const data=[{a:12,b:45,section:"first"},{section:"second",d:5,f:7},{x:23,y:78,height:200},{a:445,x:34,section:"first"}];
const res1=Object.keys(data.reduce((a,c)=>{
if(c.section) a[c.section]=1;
return a;
}, {}));
// Or, using the es6 Set object:
const res2=[...data.reduce((a,c)=>{
if(c.section) a.add(c.section);
return a;
}, new Set())];
// show results:
console.log(res1,res2);
當要收集的值是物件(而不僅僅是字串)時,第二種方法是有意義的。
uj5u.com熱心網友回復:
你可以試試這個:
var objectArray = {someting....}; // Your Object Array
var indexOfObject = objectArray.findIndex(object => {
return object.section == null;
});
objectArray.splice(indexOfObject, 1);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/512796.html
