我基本上想提取数组中的第一个对象并获取其名称。这里唯一的挑战是我正在尝试在父对象中对其进行破坏:
const exampleObject = {
collection: [{
name: "First Object",
}, {
name: "Second Object",
}],
};
const {
collection: [firstObject: {
name
}]
} = exampleObject;
console.log(firstObject);
有可能吗?
答案 0 :(得分:3)
您需要将其切换为:
{name: firstObject}
| |________ New variable name
|
|_________________ Property name
const exampleObject = {collection: [{name: "First Object",}, {name: "Second Object",}],}
const { collection: [{ name: firstObject }] } = exampleObject
console.log(firstObject)
答案 1 :(得分:1)
如果需要第一个对象的名称,请写
const {
collection: [{ name }]
} = exampleObject;
console.log(name);