我想合并覆盖两个json对象。这里的困难在于合并是在一个数组中。知道合并位置的唯一方法是使用" name"属性。
我的主要目标如下:
{
"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"
}
]
}
}
答案 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']);