繁体   English   中英

如何从对象数组中的 arrays 获取唯一值数组?

[英]How to get array of unique values from arrays within an array of objects?

我有一个给定的对象数组,例如:

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 数组?

使用flatMap迭代items ,并为每个内部数组map这些对象以返回每个bar值。 将生成的排序平面数组推入Set以删除重复项,然后将其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);

这是一个单线(虽然不确定这是最好的方法):

[...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)))]

您可以提供键路径并获取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);

您可以遍历对象数组,然后在新数组上进行查找

像这样

let uniqueBars = []; 
items.foreach = (item) => {
   const itemInNewArray = uniqueBars.find(bar => bar == item.bar);
   if (!itemInNewArray) {
      uniqueBars.push(item.bar)
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM