How to spread this array object?

77 Views Asked by At

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?

2

There are 2 best solutions below

0
On

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.

2
On

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);