我有一个像这样的对象:
var obj = {
107: {name: "test", id: 772},
124: {name: "hello", id: 123},
120: {id: 213}
}
如何从 obj
检索 name
数组,例如输出应为:["test", "hello"]
我该如何去做呢?
最佳答案
您可以使用函数reduce
、Object.values
和函数includes
来避免重复值。
var obj = {
'107': {name: "test", id: 772},
'124': {name: "hello", id: 123},
'125': {name: "hello", id: 1233},
'120': {id: 213}
}
var result = Object.values(obj).reduce((a, {name}) => {
if (name && !a.includes(name)) a.push(name);
return a;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
为了避免重复值,您也可以使用对象Set
:
var obj = {
'107': {name: "test", id: 772},
'124': {name: "hello", id: 123},
'125': {name: "hello", id: 1233},
'120': {id: 213}
}
var result = Array.from(Object.values(obj).reduce((a, {name}) => {
if (name) a.add(name);
return a;
}, new Set()).values());
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 从多个对象获取属性(如果存在),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49342404/