基于Key Property(多级)合并一组Javascript对象

时间:2014-10-20 22:57:51

标签: javascript arrays

我有一组Javascript对象,如下所示:

data = [{PK: "Country1", Prop1: "true", children:[
                {PK: "State1", Prop1: "true", children:[
                        {PK: "City1", Prop1: "Value1"}]
                }]
        },
        {PK: "Country1", Prop2: "true", children:[
                {PK: "State2", Prop2: "true", children:[
                        {PK: "City2", Prop2: "Value2"}]
                }]
        },
        {PK: "Country1", Prop3: "true", children:[
                {PK: "State2", Prop3: "true", children:[
                        {PK: "City3", Prop3: "Value3"}]
                }]
       }]

我试图根据 PK属性合并它们。 将它们视为国家,州和城市。目前每个对象都有一个国家,其子项下的属性是一个州,下面是一个城市。我希望它们合并,如果两个对象都有相同的国家,它们的状态将合并,如果两个状态相同,它们的城市将在children属性中加在一起。然后,如果一个城市有属性Prop1,状态应该表明它也具有该属性,因此 Prop1 =" true" 。这也是国家一级的结果。为了更清楚,我试图让它看起来像这样:

data = [{PK: "Country1", Prop1: "true", Prop2: "true", Prop3: "true" children:[
                {PK: "State1", Prop1: "true", children:[
                        {PK: "City1", Prop2: "Value1"}]
                },
                {PK: "State2", Prop2: "true", Prop3: "true", children:[
                        {PK: "City2", Prop2: "Value2"},
                        {PK: "City3", Prop3: "Value3"}]
                }]
       }]

我试过类似this的东西,但我不能将它包裹在子对象周围,子对象也是一个对象数组。有人可以帮我这个或者引导我找到更好的答案。谢谢!

1 个答案:

答案 0 :(得分:0)

这是一个使用我之前为json-easy-filter编写的自定义合并功能的简单脚本 希望它能为你做正确的事。请参阅此plunk

var input = ... your data here ...

var groupByPk = function (arr) {
    var res = {};
    arr.forEach(function (node) {
        if (!res[node.PK]) {
            res[node.PK] = [
                node
            ];
        } else {
            res[node.PK].push(node);
        }
    });
    return res;
};

var mergeByPk = function (arr) {
    var groups = groupByPk(arr);
    var groups2 = [];

    for ( var pk in groups) {
        var group = groups[pk];
        var ress = merge.apply(this, group);
        groups2.push(ress.value);
    }
    return groups2;
};

var mergeData = function(data){
    var mergedCountries = mergeByPk(data);
    mergedCountries.forEach(function (country) {
        var mergedStates = mergeByPk(country.children);
        country.children = mergedStates;
        mergedStates.forEach(function (state) {
            var mergedCities = mergeByPk(state.children);
            state.children = mergedCities;
        });
    });
    return mergedCountries;
};

console.log(JSON.stringify(mergeData(input), null, 4));
相关问题