-1

I have the following object:

const info = [{ name: 'John', address: 'america', gender: 'Male', job: 'SE' }];

And I need to spread this array object and get this as

form:{
   name:"John",
   address:"america",
   gender:"Male",
   job:"SE"
}

How can I do that?

Ricardo Rocha
  • 14,612
  • 20
  • 74
  • 130
prancy
  • 1
  • 2

2 Answers2

2

You don't need spread for that unless you want to make a shallow copy of the object. Instead, just use the object that's in the array:

const form = info[0];

or as a property on an object:

const obj = {form: info[0]};

At that point, form/obj.form and info[0] are both pointing to the same object.

If you do want to make a shallow copy, then spread is useful:

const form = {...info[0]};

or

const obj = {form: {...info[0]}};

There, form/obj.form points to a new object that has a copy of info[0]'s properties.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

You could destructure the array and take the wanted property as target.

const
    info = [{ "name": "John", "address": "america", "gender": "Male", "job": "SE" }],
    result = {};

[{ ...result.form }] = info;

console.log(result);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • what we have another record too. Like info = [{ "name": "John", "address": "america", "gender": "Male", "job": "SE" },{ "name": "John", "address": "america", "gender": "Male", "job": "SE" }], – prancy Dec 03 '20 at 12:04
  • what result do you expect from this? – Nina Scholz Dec 03 '20 at 12:06