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