繁体   English   中英

合并两个JSON对象数组的JSON属性(使用ramda)

[英]Merging JSON properties for two arrays of JSON objects (using ramda)

考虑一下我有两个数组,如下所示:

let a1 = [{id:1, name:'jon'}, {id:2, name:'adam'}]
let a2 = [{id:1, age:42}, {id:2, age:13}]

我想合并两个数组,以便将JSON属性合并为一个数组; 即这就是我最终要得到的结果:

[{ id: 1, name: 'jon', age: 42 },{ id: 2, name: 'adam', age: 13 }]

使用Ramda我可以执行以下操作,使我接近所需的内容,但令人讨厌的是它不在数组中-都是JSON

R.mergeDeepLeft(a1, a2)
{ '0': { id: 1, name: 'yasin', age: 42 },
  '1': { id: 2, name: 'adam', age: 13 } }

我会这样做:

  1. 同时连接a1a2 (它们不必分开)
  2. 按ID对对象进行分组,并合并共享相同ID的对象。
  3. 最终取出所有合并的对象。

 const res = pipe( concat, reduceBy(mergeLeft, {}, prop('id')), values); console.log( res(a1, a2) ); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script> <script> const {pipe, concat, reduceBy, mergeLeft, values, prop} = R; const a1 = [{id:1, name:'jon'}, {id:2, name:'adam'}]; const a2 = [{id:1, age:42}, {id:2, age:13}]; </script> 

也许不是最优雅也不可扩展的解决方案,但我会使用一些映射和散布运算符:

let a1 = [{id:1, name:'jon'}, {id:2, name:'adam'}]
let a2 = [{id:1, age:42}, {id:2, age:13}]
let a3 = a1.map(item => {
    return {...item, ...a2.find(item2 => item2.id === item.id)}
})

这是工作的小提琴https://jsfiddle.net/gshfo7pm/

尝试这个:

 let a1 = [{id:1, name:'jon'}, {id:2, name:'adam'}] let a2 = [{age:13, id:2}, {id:1, age:42}] const fn = R.pipe( R.map(R.indexBy(R.prop('id'))), R.reduce(R.mergeWith(R.mergeDeepLeft), {}), R.values ) let newArray1 = fn([a1, a2]); let newArray2 = fn([a2, a1]); console.log(newArray1); console.log(newArray2); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.js"></script> 

您可以使用R.values转换为数组,如下所示:

let a1 = [{id:1, name:'jon'}, {id:2, name:'adam'}]
let a2 = [{id:1, age:42}, {id:2, age:13}]

R.values(R.mergeWith(R.mergeLeft, a1, a2));

如果您有无序数组,则可以执行以下操作:

let a1 = [{id:1, name:'jon'}, {id:2, name:'adam'}]
let a2 = [{id:2, age:13}, {id:1, age:42}]

R.values(R.mergeWith(
  R.mergeLeft, 
  R.indexBy(R.prop('id'), a1), 
  R.indexBy(R.prop('id'), a2)
));
let concatValues = (k, l, r) =>  r
R.mergeDeepWithKey(concatValues,a1,a2)

会产生这个

{"0": {"age": 42, "id": 1, "name": "jon"}, "1": {"age": 13, "id": 2, "name": "adam"}}

它不是确切的输出,但是您可以从此开始

暂无
暂无

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

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