我正在努力从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']
}
]
答案 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);