JSON合并和覆盖数组

时间:2015-03-18 09:10:12

标签: json node.js

我想合并覆盖两个json对象。这里的困难在于合并是在一个数组中。知道合并位置的唯一方法是使用" name"属性。

  1. 有一个简单的解决方案可以用当前结构做我想要的吗?
  2. 您是否会考虑更改JSON结构,例如将名称作为关键来简化合并?
  3. 我的主要目标如下:

       {
        "servers": {
            "services": [
                {
                    "name": "api"
                    "prop1": "XXX",
                    "prop2": "XXX"
                },
                {
                    "name": "web"
                    "prop1": "XXX",
                    "prop2": "XXX"
                }
            ]
        }
    }
    

    "网络"服务需要覆盖:

    {
        "servers": {
            "services": [
                {
                    "name": "web"
                    "prop1": "overriden value"
                }
            ]
        }
    }
    

    结果对象应为:

    {
        "servers": {
            "services": [
                {
                    "name": "api"
                    "prop1": "XXX",
                    "prop2": "XXX"
                },
                {
                    "name": "web"
                    "prop1": "overriden value",
                    "prop2": "XXX"
                }
            ]
        }
    }
    

1 个答案:

答案 0 :(得分:2)

我制作了一个节点包,它有点矫枉过正,but it will do the job, called json_merger

// https://www.npmjs.com/package/json_merger
var json_merger = require('json_merger');

var a = {
    "servers": {
        "services": [
            {
                "name": "api"
                "prop1": "XXX",
                "prop2": "XXX"
            },
            {
                "name": "web"
                "prop1": "XXX",
                "prop2": "XXX"
            }
        ]
    }
};

var b = {
    "servers": {
        "services": [
            {
                "@match": "[name=web]",
                "prop1": "overriden value"
            }
        ]
    }
}

var result = json_merger.merge(a, b);

但是,如果使用任何合适的合并工具,它将坚持索引:

// This is pseudo code:
var a = [{...}, {...}, {...}]

// to override object at index 1 you should be able to do this:
merge(a, [{/*intentional empty object, so we get index up*/}, 'new value at index 1']);