I want to loop through and add properties from an array to another array: Array1:
const users = [
{
"id":"112",
"firstName":"a",
"lastName":"b",
"address":[
{
"apartment":"1",
"street":"north"
}
]
},
{
"id":"113",
"firstName":"e",
"lastName":"f",
"address":[
{
"apartment":"2",
"street":"north"
}
]
},
{
"id":"114",
"firstName":"i",
"lastName":"j",
"address":[
{
"apartment":"3",
"street":"south"
}
]
},
{
"id":"1151",
"firstName":"o",
"lastName":"p",
"address":[
{
"apartment":"4",
"street":"west"
}
]
}
]
So, I have an empty array const usersInfo = []
I want to add only id
and address
in usersInfo
from users
array
What I am trying to do below:
const result = this.usersInfo.map(item => {
users.forEach((element) => {
item.id = element.id,
item.address = element.address.map(r => {
return {
apartment: r.apartment,
street: r.street
};
}),
});
});
But this returns an Empty array as a result.
I need output like below
const usersInfo = [
{
id: '112',
address:[{
apartment:'1',
street: 'north'
}]
},
{
id: '113',
address:[{
apartment:'2',
street: 'north'
}]
},
{
id: '114',
address:[{
apartment:'3',
street: 'south'
}]
},
{
id: '1151',
address:[{
apartment:'4',
street: 'west'
}]
}
]
You can do something like below:
const usersInfo = users.map(user => ({id: user.id, address: user.address}))
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.