首页 > 解决方案 > Javascript在2个对象数组上按键合并和替换值

问题描述

我想在 Javascript 中合并 2 个对象数组,源数组类似于:

padding = [{'t': 1, 'c': 0}, {'t': 2, 'c': 0}, {'t': 3, 'c': 0}]
data = [{'t': 3, 'c': 5}]

结果应如下所示:

result = [{'t': 1, 'c': 0}, {'t': 2, 'c': 0}, {'t': 3, 'c': 3}]

请注意,这是通过匹配data填充的。我尝试了各种方法,例如 jQuery ,但是它没有正确输出。padding't'$.extend({}, padding, data)

感谢您分享一些东西。谢谢。

编辑 1(2020 年 4 月 10 日)

正如@codemaniac 指出的那样,我有一个错字,结果应该是:

result = [{'t': 1, 'c': 0}, {'t': 2, 'c': 0}, {'t': 3, 'c': 5}]

附加(2020 年 4 月 10 日)

我的padding长度为 1000,因为data它应该是paddingkey的子集't'

我正在寻找“合并”和“替换” into的有效方法,有些人称之为“加法”,因为它总是会为每个对象填充。datapaddingpadding'c': 0

lodash如果可能的话,我不介意尝试JS 实用程序。

标签: javascriptarraysobjectmergelodash

解决方案


如果您要合并数组,但还要用给定 t 值的对象替换来自padding的对象,这是一种方法:data

const padding = [{'t': 1, 'c': 0}, {'t': 2, 'c': 0}, {'t': 3, 'c': 0}];
const data = [{'t': 3, 'c': 5}, {'t': 5, 'c': 6}];

const merged = [];

// loops through the objects in padding. If it finds an object in data that has the same t value, it chooses the object from data to add to the merged array. Otherwise, it uses the object from padding

padding.forEach((obj) => {
 	let dataObj = data.find(dataObj => dataObj.t === obj.t);
	if (dataObj) {
		merged.push(dataObj);
	} else {
		merged.push(obj);
	}
});

// loops through the data array. If there are any objects in data with a t value not in any padding object, it adds this to the merged array

data.forEach((obj) => {
	let paddingObj = padding.find(paddingObj => obj.t === paddingObj.t);
	if (!paddingObj) {
		merged.push(obj);
	}
});

console.log(merged);


推荐阅读