解构数组中的嵌套对象

我基本上想拉出数组中的第一个对象并获取它的名称。这里唯一的挑战是我试图在父对象中解构它:


const exampleObject = {

  collection: [{

    name: "First Object",

  }, {

    name: "Second Object",

  }],

};


const {

  collection: [firstObject: {

    name

  }]

} = exampleObject;


console.log(firstObject);

有可能吗?


蝴蝶刀刀
浏览 206回答 2
2回答

撒科打诨

您需要将其切换为:{name: firstObject}  |        |________ New variable name  |      |_________________ Property nameconst exampleObject = {collection: [{name: "First Object",}, {name: "Second Object",}],}const { collection: [{ name: firstObject }] } = exampleObjectconsole.log(firstObject)

慕丝7291255

如果你需要第一个对象的名字,你应该写const {  collection: [{ name }]} = exampleObject;console.log(name);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript