繁体   English   中英

Javascript 在 2 个对象数组上按键合并和替换值

[英]Javascript merge and replace value by key on 2 array of objects

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

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}]

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

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

编辑 1(2020 年 4 月 10 日)

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

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

附加(2020 年 4 月 10 日)

我的padding长度为 1000,对于data ,它应该是键't' padding的子集。

我正在寻找将data “合并”和“替换”到padding有效方法,有些人称之为“添加”,因为对于每个 object, padding总是用'c': 0填充。

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

我假设您想要添加,以获得元素的正确大小(填充 + 宽度)

 const padding = [{ t: 1, c: 0, }, { t: 2, c: 0, }, { t: 3, c: 0, }]; const data = [{ t: 3, c: 5, }]; // Use a reduce to build the new array function mergeData(d1, d2) { return d2.reduce((tmp, x) => { // Check if the array already contains the key 't' const found = tmp.find(y => yt === xt); // If it does, add 'c' together if (found) { found.c += x.c; } else { // else, add the missing entry tmp.push(x); } return tmp; }, d1); } console.log(mergeData(data, padding));

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

 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 at 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);

您可以使用Mapmap

  • 首先使用 Map 构建一个 Map Object 从数据以t为键和c
  • 现在循环填充数组并查看t是否存在 Map 我们使用来自 Map 的c的值,否则仅来自当前元素

 const padding = [{'t': 1, 'c': 0}, {'t': 2, 'c': 0}, {'t': 3, 'c': 0}]; const data = [{'t': 3, 'c': 5}]; const mapper = new Map(data.map(( { t, c } ) => [t, c] )); const final = padding.map(({ t, c }) => ({ t, c: mapper.has(t)? mapper.get(t): c })); console.log(final);

我不确定效率,但这段代码有效并且可读性很好

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

data.forEach(d => {
    padding.find(p => p.t === d.t).c = d.c
})

console.log(padding)
// OUTPUT: [ { t: 1, c: 0 }, { t: 2, c: 0 }, { t: 3, c: 5 } ]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM