简体   繁体   English

如何使用解构将数组值添加到 object?

[英]How can I add array values to an object using destructuring?

I have variables here firstName which is Faisal and lastName which is Iraqi .我在这里有变量firstNameFaisallastNameIraqi

let str = "Faisal Iraqi";
let [firstName, lastName] = str.split(" ");
console.log(firstName, lastName);
console.log(str.split(" "));

so I should add this properties to my new object using destructuring:所以我应该使用解构将此属性添加到我的新 object 中:

let obj = {};

obj must return firstName: "Faisal", lastName: "Iraqi" obj 必须返回firstName: "Faisal", lastName: "Iraqi"

Simply add them to the object:只需将它们添加到 object 中:

let obj = {firstName, lastName};

So the whole code looks like:所以整个代码看起来像:

let str = "Faisal Iraqi";
let [firstName, lastName] = str.split(" ");
let obj = {firstName, lastName};
console.log(obj);

Instead of using a destructuring assignment as you create new variables, you can directly destructure into the object properties:您可以在创建新变量时直接解构为 object 属性,而不是使用解构赋值:

 let str = "Faisal Iraqi"; let obj = {}; [obj.firstName, obj.lastName] = str.split(" "); console.log(obj);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM