基于公共属性合并2个json数组对象 [英] Merge 2 json array objects based on a common property

查看:185
本文介绍了基于公共属性合并2个json数组对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个Json数组,并且具有一些公共字段.但是它们不是按任何特定顺序排序的.我希望能够基于属性将它们合并.

I got 2 Json arrays with some common field. But they are not sorted in any specific order. I want to be able to merge them based on a property.

var merge = require('deepmerge');
var one = [{
  id:1
},
{
  id:2
}];
var two = [{
  id:2,
  name:"test1"
},
{
  id:1,
  name:"test2"
}];

console.log(merge(one,two));

deepmerge导致盲合并,第一个元素与另一个数组中的第一个元素盲合并.

deepmerge results in blind merge, first element with first element from the other array.

[ { id: 2, name: 'test1' }, { id: 1, name: 'test2' } ]

我知道有可能手动遍历一个数组,从另一个数组中找到匹配的节点,然后合并它们……想知道是否有任何库可以做到这一点.有想法吗?

I know its possible to manually iterate thru one array, find the matching node from the other array and merge them...wondering if there is any library to do this. Thoughts?

推荐答案

您可以使用一个函数并定义公用密钥,合并应该在公用密钥上进行分组.它适用于未排序的数据.

You could use a function and define the common key, on which the merging should group. It works with unsorted data.

function merge(array, key) {
    var r = [],
        hash = Object.create(null);

    array.forEach(function (a) {
        a.forEach(function (o) {
            if (!hash[o[key]]) {
                hash[o[key]] = {};
                r.push(hash[o[key]]);
            }
            Object.keys(o).forEach(function (k) {
                hash[o[key]][k] = o[k];
            });
        });
    });
    return r;
}

var one = [{ id: 1, score: 100 }, { id: 2, score: 200 }, { id: 4, score: 400 }],
    two = [{ id: 2, name: "test1" }, { id: 1, name: "test2" }, { id: 3, name: "test3" }],
    merged = merge([one, two], 'id');

console.log(merged);

这篇关于基于公共属性合并2个json数组对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆