简体   繁体   中英

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

I have variables here firstName which is Faisal and lastName which is Iraqi .

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:

let obj = {};

obj must return firstName: "Faisal", lastName: "Iraqi"

Simply add them to the 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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