如何基于对象数组更新复杂的json对象

时间:2020-08-27 05:40:32

标签: arrays json angular typescript

我有2个数据结构,如下所示

数据1:

{
  purchaceOrder: [{
      name: "Purchase Order",
      version: 1,
      description: "purchase order process",
      saved: true,
      visibility: true
    },
    {
      name: "Purchase Order",
      version: 2,
      description: "purchase order process",
      saved: false,
      visibility: true
    }
  ],
  requestOrder: [{
      name: "Request Order",
      version: 1,
      description: "request order process",
      saved: true,
      visibility: true
    },
    {
      name: "Request Order",
      version: 2,
      description: "request order process",
      saved: false,
      visibility: true
    }
  ],
  cancelOrder: [{
    name: "Cancel Order",
    version: 1,
    description: "cancel order process",
    saved: false,
    visibility: false
  }]
}

data2:

[
  {
    id: "dwffrgefg68964",
    name: "Purchase Order",
    version: 1
  },
  {
    id: "emffrgefg68964",
    name: "Purchase Order",
    version: 2
  },
  {
    id: "iuffrgefg68964",
    name: "request Order",
    version: 1
  }
]
  

我想根据名称过滤data1,如果在data2中找不到进程名称,则将data2中的id添加到data1中的每个对象,并删除data1中的整个对象/空数组,如下所示

最终结果:

{
  purchaceOrder: [{
      id: "dwffrgefg68964"
      name: "Purchase Order",
      version: 1,
      description: "purchase order process",
      saved: true,
      visibility: true
    },
    {
      id: "emffrgefg68964"
      name: "Purchase Order",
      version: 2,
      description: "purchase order process",
      saved: false,
      visibility: true
    }
  ],
  requestOrder: [{
    id: "iuffrgefg68964"
    name: "Request Order",
    version: 1,
    description: "request order process",
    saved: true,
    visibility: true
  }]
}

我尝试了各种解决方案,但无法获得预期的结果。这就是我所拥有的:

getAllProcess(){
for (let key in data1) {
  var temp1 = data1[key];
  for (let i = 0; i < temp1.length; i++) {
      const reqModel = data2.find(process=> process.name === temp1[i].name&& process.version === temp1[i].version);
    if(reqModel){
      temp1[i].id=reqModel.id;
        data1[key][i]=temp1[i];
    }
    }}
    return data1;
}

2 个答案:

答案 0 :(得分:3)

您的代码已接近;您只需要删除data1中没有相应值的条目{}:

data2

答案 1 :(得分:0)

我为您制定了某些算法。它正在使用空数组创建data1,然后通过其data2属性推送name个项目。

const data1 = {
  requestOrder: [],
  purchaseOrder: [],
  cancelOrder: []
};
const data2 = ...;
data2.forEach((d) => {
  if (d.name == 'Request Order') {
    data1.requestOrder.push(d);
  } else if (d.name == 'Purcase Order') {
    data1.purchaseOrder.push(d);
  } else {
    data1.cancelOrder.push(d);
  }
});