如何从数组中查找数组中的特定元素

时间:2018-11-23 08:09:51

标签: javascript angular

我正在努力从sampledata中的历史值中添加一个条目

  let sampledata = [
      {
      headerKey: "FirstName",
      value: "Dave",
     }, {
        headerKey: "LastName",
        value: "K",
      }]

 // add here in history value


 let addHere= [
      {
        headerKey: 'FirstName',
        historyValue: ['abc', 'ghi', 'sss']
       },
      {
        headerKey: 'LastName',
        historyValue: ["'oo', 'ppp', 'qqqq']
      }
    ]

 //Output should be

 //increment value in history value after comparing the header key from sampledata

 let addHere= [
      {
        headerKey: 'FirstName',
        historyValue: ['Aman', 'abc', 'ghi', 'sss']
       },
      {
        headerKey: 'LastName',
        historyValue: ['k', oo', 'ppp', 'qqqq']
      }
    ]

1 个答案:

答案 0 :(得分:0)

您可以使用forEach()循环并在addHere数组中查找现有对象的内部,以获取与headerKey匹配的对象,然后更新historyValue数组:

let sampledata = [{
  headerKey: "FirstName",
  value: "Dave",
}, {
  headerKey: "LastName",
  value: "K",
},
{
  headerKey: "NotExist",
  value: "someVal",
}]

let addHere = [{
    headerKey: 'FirstName',
    historyValue: ['abc', 'ghi', 'sss']
  },
  {
    headerKey: 'LastName',
    historyValue: ['oo', 'ppp', 'qqqq']
  }
];

sampledata.forEach((item)=>{
  var existItem = addHere.find(({headerKey}) => headerKey === item.headerKey);
  if(existItem){
    //if you want to insert that in index 0
    //else use existItem.historyValue.push(item.value);
    existItem.historyValue.splice(0, 0, item.value);
  } else {
    addHere.push({
      headerKey: item.headerKey,
      historyValue: [item.value]
    });
  }
});
console.log(addHere);