[英]How to add some properties from one array to another in typescript
I want to loop through and add properties from an array to another array: Array1:我想循环并将属性从一个数组添加到另一个数组: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所以,我有一个空数组const usersInfo = []
我只想在users
数组中的usersInfo
中添加id
和address
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我需要 output 如下所示
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}))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.