试图提高我的 JS 排骨。
有没有一种更简洁的方法可以通过键从嵌套对象中从下面的数组中检索属性值,删除重复项并按字母顺序对其进行排序?
这是我所拥有的:
getObjectValues(array, key){
var unique = [];
array.forEach(function(item){
item[key].forEach(function(value){
if (unique.indexOf(value) < 0) {
unique.push(value)
}
})
});
return unique.sort();
},
对象数组示例:[
{ name: 'hello', value: ['a','b','c']},
{ name: 'hello', value: ['a','b','c']},
{ name: 'hello', value: ['a','b','c']}
]
预期输出应该是一个数组:var array = ['a','b','c']
最佳答案
您可以只使用一个 Set,并将所有项目添加到其中:
let arr = [
{ name: 'hello', value: ['a','b','c']},
{ name: 'hello', value: ['a','b','c']},
{ name: 'hello', value: ['a','b','c']}
]
console.log(
Array.from(
new Set(
arr.reduce(
(carry, current) => [...carry, ...current.value],
[]
)
)
).sort()
)
关于javascript - ES6方式 - 按键从嵌套数组中获取唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62942904/