Javascript - 比较两个数组对象并附加值
2019-10-11
920
如何比较两个数组对象,并将第一个数组对象附加到匹配条件键上,第二个数组对象也是如此?请提出建议。
例如,在下面的数据中,我需要将
vale_data
服务密钥与
sli_data
服务密钥进行比较,如果匹配,则将
sli_data
vol_sli 键值附加到
vale_data
。
var vale_data = [
{service: "allocateorder", vol_slo: "10000"},
{service: "cancelorder", vol_slo: "10000"},
{service: "adviceorder", vol_slo: "10000"}]
var sli_data = [
{service: "allocateorder", vol_sli: "0.9484949"},
{service: "cancelorder", vol_sli: "0.242322"}]
我尝试过以下方法,但没有成功。
var vale_data = [
{service: "allocateorder", vol_slo: "10000"},
{service: "cancelorder", vol_slo: "10000"},
{service: "adviceorder", vol_slo: "10000"}]
var sli_data = [
{service: "allocateorder", vol_sli: "0.9484949"},
{service: "cancelorder", vol_sli: "0.242322"}]
for (i=0; i<Object.keys(vale_data).length; i++) {
for (j=0; j<Object.keys(sli_data).length; j++) {
if (Object.values(vale_data)[i]['service'] == Object.values(sli_data)[i]['service']) {
vale_data.map(item => {item.vol_sli = Object.values(sli_data)[j]['vol_sli'] })
}
}
}
预期输出:
vale_data = [
{service: "allocateorder", vol_slo: "10000", vol_sli: "0.9484949"},
{service: "cancelorder", vol_slo: "10000", vol_sli: "0.242322"},
{service: "adviceorder", vol_slo: "10000", vol_sli: ""} ]
实际输出:
error: Uncaught TypeError: Cannot read property 'service' of undefined
3个回答
您可以尝试此操作,方法是创建一个对象作为映射,然后使用它来获取输出数组。使用 Javascript MAP 来存储结果
var vale_data = [
{service: "allocateorder", vol_slo: "10000"},
{service: "cancelorder", vol_slo: "10000"},
{service: "adviceorder", vol_slo: "10000"}]
var sli_data = [
{service: "allocateorder", vol_sli: "0.9484949"},
{service: "cancelorder", vol_sli: "0.242322"}]
var sli_dataMap = new Map(sli_data.map(({service,vol_sli}) => ([service,vol_sli])));
vale_data = vale_data.map(obj => ({...obj,vol_sli:sli_dataMap.get(obj.service) || ''}));
console.log(vale_data);
Dhananjai Pai
2019-10-11
遍历每个数组,如果一个 sli.service 与一个 vale.service 相同,则向该 vale 添加一个等于 sli.vol_sli 的 vol_sli 字段。
vale_data.forEach(function (vale) {
sli_data.forEach(function (sli) {
if (sli.service === vale.service) {
vale.vol_sli = sli.vol_sli;
}
})
});
Ilan Schemoul
2019-10-11
var vale_data = [
{service: "allocateorder", vol_slo: "10000"},
{service: "cancelorder", vol_slo: "10000"},
{service: "adviceorder", vol_slo: "10000"}]
var sli_data = [
{service: "allocateorder", vol_sli: "0.9484949"},
{service: "cancelorder", vol_sli: "0.242322"}]
var result = vale_data.map(vale_data_value => {
const check_sli_data = sli_data.find(sli_data_value => sli_data_value.service === vale_data_value.service );
if(check_sli_data){
vale_data_value.vol_sli = check_sli_data.vol_sli
}
return vale_data_value;
});
console.log(result)
vijay kumar
2019-10-11