我有一个映射的数组对象,现在我需要从该数组的子对象中获取唯一值。
const arr=[
{
name: 'name1',
functions:{
0:{
name:'some1',
property: 'string'
},
1:{
name:'some1',
property: 'string'
},
2:{
name:'some3',
property: 'number'
}
}
},
]
<div>
{
arr.map((item, index) => {
let ars=[]
//console.log(item.functions)
for(const key in item.functions){
if(ars.indexOf(item.functions[key])>1){
ars.push(item.functions[key])
}
}
console.log(ars)
return <div key={index}>
<h2>{item.name}</h2>
{
ars.map((i)=>(
<p>{i.name}</p>
))
}
</div>
})
}
</div>
我需要获取这样的值: 一些1 一些3
所以我只需要从属性字符串中获取一个名称。对于数字来说,只有一个名称。
最佳答案
您可以创建一个Set
对于属性
。如果尚未添加属性
,请将属性的名称
添加到数组中。
const arr = [{
name: 'name1',
functions: {
0: {
name: 'some1',
property: 'string'
},
1: {
name: 'some2',
property: 'string'
},
2: {
name: 'some3',
property: 'number'
}
}
}]
const propertySet = new Set,
names = []
for (const { functions } of arr) {
Object.values(functions).forEach(o => {
if (!propertySet.has(o.property)) {
names.push(o.name);
propertySet.add(o.property)
}
})
}
console.log(names)
关于javascript - 如何从对象数组中获取唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56450135/