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

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

我这里有变量 firstNameFaisallastNameIraqi.

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

所以我应该使用解构将这些属性添加到我的新对象中:

let obj = {};

obj 必须 return firstName: "Faisal", lastName: "Iraqi"

您可以直接解构为对象属性,而不是在创建新变量时使用解构赋值:

let str = "Faisal Iraqi";
let obj = {};

[obj.firstName, obj.lastName] = str.split(" ");

console.log(obj);

只需将它们添加到对象中:

let obj = {firstName, lastName};

所以整个代码看起来像:

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