[英]Merge two array of objects with skipping objects that has same ID property
[英]Merge two array of objects by ID?
我有以下对象数组
firstAry = [{
"status": "Creating",
"datacenter-id": "1test",
"datacenter-name": "1name"
}, {
"status": "Creating",
"datacenter-id": "2test",
"datacenter-name": "2name"
}, {
"status": "Creating",
"datacenter-id": "id1",
"datacenter-name": "data6"
}, {
"status": "Creating",
"datacenter-id": "id2",
"datacenter-name": "data7"
}]
secondAry = [
{
"status": "Creating",
"cluster-id": "1test",
"cluster-name": "clu1",
"datacenter-id": "null"
},
{
"status": "Creating",
"cluster-id": "1test1",
"cluster-name": "clu1",
"datacenter-id": "id1"
},
{
"status": "Creating",
"cluster-id": "1test113",
"cluster-name": "clu11",
"datacenter-id": "id1"
},
{
"status": "Creating",
"cluster-id": "2test2",
"cluster-name": "clu2",
"datacenter-id": "id2"
},
{
"status": "Creating",
"cluster-id": "2test22",
"cluster-name": "clu22",
"datacenter-id": "id2"
}
]
我想在表中显示 3 个字段 - 表中的status
、 cluster-name
和datacenter-name
。 问题是我得到status
, cluster-name
在secondAry
但是datacenter-name
在越来越firstAry
。 所以我想在datacenter-id
的基础上合并这两个数组。 如果没有匹配的datacenter-id
则应将datacenter-name
字段显示为空白。 我想补充的datacenter-name
在secondAry
通过匹配的ID firstAry
并获得datacenter-name
字段,在其添加secondAry
。
结果对象数组应该是这样的
Result = [
{ "status": "Creating", "cluster-id": "1test", "cluster-name": "clu1", "datacenter-id": "null" ,"datacenter-name": "null" },
{ "status": "Creating", "cluster-id": "1test1", "cluster-name": "clu1", "datacenter-id": "id1", "datacenter-name": "data6" },
{ "status": "Creating", "cluster-id": "1test113", "cluster-name": "clu11", "datacenter-id": "id1" , "datacenter-name": "data6" },
{ "status": "Creating", "cluster-id": "2test2", "cluster-name": "clu2", "datacenter-id": "id2" ,"datacenter-name": "data7" },
{ "status": "Creating", "cluster-id": "2test22", "cluster-name": "clu22", "datacenter-id": "id2" ,"datacenter-name": "data7" } ]
我尝试了过滤器方法,但它删除了没有匹配 id 的元素。 请帮助如何实现这一目标?
this.secondAry.forEach(x=>{
const data=this.firstAry.find(f=>f['datacenter-id']==x['datacenter-id'])
x['datacenter-name']=data?data['datacenter-name']:''
})
注意:在使用“-”之前,最好使用驼峰命名法。 使用“-”时,您需要使用obj['property']
访问该属性,否则为 simpe obj.property
通过将第一个数组与第二个数组进行比较,从第一个数组中找到匹配的对象。 修改结果并返回一个新的修改后的数组。
const result = secondAry.map(item => {
const searchedItem = firstAry.find(fItem => fItem['datacenter-id'] ===
item['datacenter-id'] );
if(searchedItem && Object.keys(searchedItem).length > 0 ){
item['datacenter-name'] = searchedItem['datacenter-name']
}else{
item['datacenter-name'] = 'null'
}
return item;
});
console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.