我有一個給定的物件陣列,例如:
var items = [
{item: [{foo: 21, bar: 'a' }, {foo: 5,bar: 'e'},{foo: 167, bar: 'c'}]},
{item: [{foo: 42, bar: 'a' }, {foo: 45,bar: 'd'},{foo: 7, bar: 'c'}]},
{item: [{foo: 99, bar: 'b' }, {foo: 35,bar: 'c'},{foo: 22, bar: 'e'}]},
{item: [{foo: 31, bar: 'e' }, {foo: 22,bar: 'd'},{foo: 12, bar: 'a'}]}
]
我想得到一個新陣列,它回傳所有條形值的唯一值,所以它看起來像:
var uniqueBars = ['a','b','c','d','e'];
我有一個通過回圈遍歷所有專案的解決方案,但我猜有一種更有效的方法可以使用 ES6 特性來做到這一點。
有沒有辦法使用 ES6 特性創建上面的 uniqueBars 陣列?
uj5u.com熱心網友回復:
遍歷這些物件items的flatMap每個內部陣列map以回傳每個bar值。將生成的排序后的平面陣列推入 aSet以洗掉重復項,然后spread將其放回陣列中,以便您可以記錄重復資料。
const items=[{item:[{foo:21,bar:"a"},{foo:5,bar:"e"},{foo:167,bar:"c"}]},{item:[{foo:42,bar:"a"},{foo:45,bar:"d"},{foo:7,bar:"c"}]},{item:[{foo:99,bar:"b"},{foo:35,bar:"c"},{foo:22,bar:"e"}]},{item:[{foo:31,bar:"e"},{foo:22,bar:"d"},{foo:12,bar:"a"}]}];
// For each `obj.item.map` you'll get a nested array of
// bar values from each object. Use `flatMap` on that array
// to get all the values into one array, and then sort it
const flattened = items.flatMap(obj => {
return obj.item.map(inner => inner.bar);
}).sort();
// Pass the flattened array into a new Set
// and use spread to work that set into a new array
const deduped = [...new Set(flattened)];
console.log(deduped);
uj5u.com熱心網友回復:
您可以遍歷物件陣列,然后在新陣列上進行查找
像這樣
let uniqueBars = [];
items.foreach = (item) => {
const itemInNewArray = uniqueBars.find(bar => bar == item.bar);
if (!itemInNewArray) {
uniqueBars.push(item.bar)
}
}
uj5u.com熱心網友回復:
您可以提供鍵路徑并獲取 a 的值Set。
const
getValues = (data, [key, ...keys]) => data.flatMap(o => keys.length
? getValues(o[key], keys)
: o[key]
),
items = [{ item: [{ foo: 21, bar: 'a' }, { foo: 5, bar: 'e' }, { foo: 167, bar: 'c' }] }, { item: [{ foo: 42, bar: 'a' }, { foo: 45, bar: 'd' }, { foo: 7, bar: 'c' }] }, { item: [{ foo: 99, bar: 'b' }, { foo: 35, bar: 'c' }, { foo: 22, bar: 'e' }] }, { item: [{ foo: 31, bar: 'e' }, { foo: 22, bar: 'd' }, { foo: 12, bar: 'a' }] }],
keys = ['item', 'bar'],
unique = [...new Set(getValues(items, keys))];
console.log(...unique);
uj5u.com熱心網友回復:
這是一個單線(雖然不確定這是最好的方法):
[...new Set(items.map(obj => obj.item.map(o => o.bar)).flat())]
正如@Mulan 和@Andy 所建議的那樣,而不是[].map().flat(),更喜歡flatMap():
[...new Set(items.flatMap(obj => obj.item.map(o => o.bar)))]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/463127.html
上一篇:C-字串陣列的動態記憶體分配問題
