我要基于另一个数组中存在的键更新数组数据,如果不存在键,则输出值为0的数据以及相应的键
let data = [{
ORIGEN: "WB716594",
"Gestor Ericsson OSS": 1
}, {
ORIGEN: "MM-LORC-AGUI-L3-11_760525",
"MM-LORC-AGUI-L3-11_760525": 1
}];
let keyValue = ["Gestor Ericsson OSS",
"MM-LORC-AGUI-L3-11_760525",
"Gestor HUA U2KVIA",
"5620SAM"
]
数据中不存在“ Gestor HUA U2KVIA”和“ 5620SAM”,因此应按以下内容添加
Output = [{ORIGEN: "WB716594", Gestor Ericsson OSS: 1, "MM-LORC-AGUI-L3-11_760525":0,Gestor HUA U2KVIA:0,5620SAM:0},
{ORIGEN: "MM-LORC-AGUI-L3-11_760525", MM-LORC-AGUI-L3-11_760525: 1,Gestor Ericsson OSS: 0,Gestor HUA U2KVIA:0,5620SAM:0}
]
答案 0 :(得分:1)
您可以创建一个对象,其中将keyValue
个数组项作为键,将0
作为值。然后使用data
遍历map
数组,并使用Object.assign
获取每个项目的合并对象:
const data = [{ORIGEN:"WB716594","Gestor Ericsson OSS":1},{ORIGEN:"MM-LORC-AGUI-L3-11_760525","MM-LORC-AGUI-L3-11_760525":1}],
keyValue = ["Gestor Ericsson OSS","MM-LORC-AGUI-L3-11_760525","Gestor HUA U2KVIA","5620SAM"]
const defaultObj = Object.assign({}, ...keyValue.map(key => ({ [key]: 0 })));
const output = data.map(obj => Object.assign({}, defaultObj, obj));
console.log(output)