-1

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"

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
qLeima-
  • 3
  • 2
  • 1
    _"so I should add this properties to my new object using destructuring"_ - Why? Why not `let obj = { firstName: firstName, lastName: lastName }`? – Andreas Jan 13 '21 at 15:02

2 Answers2

2

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);
Pranjal Nadhani
  • 106
  • 1
  • 5
1

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);
VLAZ
  • 26,331
  • 9
  • 49
  • 67