![](/img/trans.png)
[英]FlatMap vs Reduce for mapping and filtering - is one recommended over the other?
[英]Normal Mapping vs Reduce
我正在嘗試將一個對象轉換為只有鍵和值的單個數組。 我嘗試了兩種不同的方法。 雖然我在第一次嘗試中成功了,但使用 reduce 卻無法得到結果。 請讓我知道是否有更好的方法來實現相同的目標。 謝謝你。
var demoArr = [
{
"results": [
{
"listing_id": 10544193
},
{
"listing_id": 4535435
}
],
"results1": [
{
"listing_id": 1054419363
},
{
"listing_id": 432535435
}
]
}
];
let aaa = [];
// demoArr.map(x => { (before)
demoArr.forEach(x => { //(after)
let ss = Object.values(x);
// ss.map(y => { (before)
ss.forEach(y => { //(after)
y.forEach(k => {
aaa.push({"listing_id" : k.listing_id});
})
});
});
結果如下。
[{"listing_id":10544193},{"listing_id":4535435},{"listing_id":1054419363},{"listing_id":432535435}]
有沒有更好的方法來實現上述目標? 也許通過使用減少? 我試過但沒有得到結果。
var ds = demoArr.reduce((a,value) => {
a[value.listing_id] = a[value.listing_id] ? a[value.listing_id] : value
return a
},{});
這是使用flatMap()
和Object.values
的一種方法,然后展平結果。 以這種方式使用 Object.values 作為參數是將 map 參數直接應用到 Object.values 方法並返回結果的簡寫
var demoArr = [{ "results": [{ "listing_id": 10544193 }, { "listing_id": 4535435 } ], "results1": [{ "listing_id": 1054419363 }, { "listing_id": 432535435 } ] }]; let output = demoArr.flatMap(Object.values).flat(); console.log(output)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.