繁体   English   中英

按 ID 合并两个对象数组?

[英]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 个字段 - 表中的statuscluster-namedatacenter-name 问题是我得到statuscluster-namesecondAry但是datacenter-name在越来越firstAry 所以我想在datacenter-id的基础上合并这两个数组。 如果没有匹配的datacenter-id则应将datacenter-name字段显示为空白。 我想补充的datacenter-namesecondAry通过匹配的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM