javascript - 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
它应该是padding
key的子集't'
。
我正在寻找“合并”和“替换” into的有效方法,有些人称之为“加法”,因为它总是会为每个对象填充。data
padding
padding
'c': 0
lodash
如果可能的话,我不介意尝试JS 实用程序。
解决方案
如果您要合并数组,但还要用给定 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);
推荐阅读
- python - ModuleNotFoundError:“没有命名的模块
",从 Django 部署到 Heroku 时 - tampermonkey - 为什么 https://news.google.com/* 的 Tampermonkey 脚本会出现在 https://www.nytimes.com/ 的菜单中?
- r - ggplot2 geom_bar 颜色条由一列和轮廓由另一列
- c# - 如何在 C# 中将非托管类型转换为托管类型?
- javascript - 将画布转换为blob时出现react-crop-image错误
- ibm-cloud - 如何在 Xbox 游戏栏的小部件中添加更多应用?
- sql - PostgreSQL - 从连接列连接索引
- firebase - TextEditingController 在 .clear() 之后不清除文本
- javascript - 如何在另一个网页而不是控制台中打印 Pyodide 的结果?
- c# - C# 中的 Kafka 消费者 - 跳过对当前消息的进一步处理