我有两个JSON,我想在JavaScript中添加两个JSON(将JSOB对象加入JSON A),
JSON A:-
activecontroller
JSON B:-
{
"data": [{
"id": 1,
"subgroup": "1",
"power": "2",
"grp": "1"
}, {
"id": 1,
"subgroup": "1",
"power": "1",
"grp": "1"
}, {
"id": 2,
"subgroup": "1",
"power": "1",
"grp": "2"
}, {
"id": 3,
"subgroup": "2",
"power": "1",
"grp": "2"
}, {
"id": 4,
"subgroup": "1",
"power": "1",
"grp": "3"
}, {
"id": 5,
"subgroup": "2",
"power": "1",
"grp": "2"
}, {
"id": 6,
"subgroup": "2",
"power": "1",
"grp": "1"
}, {
"id": 7,
"subgroup": "1",
"power": "1",
"grp": "4"
}, {
"id": 1,
"subgroup": "3",
"power": "2",
"grp": "4"
}
}
键名称在JSON A和JSON B中相似。我们可以看到{
"data": [{
"id": 1,
"subgroup": "3",
"power": "2",
"grp": "4"
}, {
"id": 1,
"subgroup": "4",
"power": "1",
"grp": "3"
}
}
和subgroup 3
分别仅出现在subgroup 4
和grp 4
中(调查JSON B)。我想将JSON B中的每个grp 3
添加到JSON A中的每个subgroup
中(除了grp
中已经存在这些grp
的地方。像JSON A中一样包含subgroup
和subgroup 3
的条目,我们将跳过该条目。) grp 4
,Id
的值将分别相似。因此,我们要在power
中添加subgroup 3
并在grp 1, 2, 3
中添加subgroup 4
。对于group 1, 2, 4
,subgroup 3
和power
的值分别为id
,对于2, 1
,subgroup 4
和power
的值分别为{ {1}}。
最终JSON输出应为
id
我可以将对象添加到JSON中,
1, 1
从JSON B加入JSON A并跳过{
"data": [{
"id": 1,
"subgroup": "1",
"power": "2",
"grp": "1"
}, {
"id": 1,
"subgroup": "1",
"power": "1",
"grp": "1"
}, {
"id": 2,
"subgroup": "1",
"power": "1",
"grp": "2"
}, {
"id": 3,
"subgroup": "2",
"power": "1",
"grp": "2"
}, {
"id": 4,
"subgroup": "1",
"power": "1",
"grp": "3"
}, {
"id": 5,
"subgroup": "2",
"power": "1",
"grp": "2"
}, {
"id": 6,
"subgroup": "2",
"power": "1",
"grp": "1"
}, {
"id": 7,
"subgroup": "1",
"power": "1",
"grp": "4"
}, {
"id": 1,
"subgroup": "3",
"power": "2",
"grp": "4"
}, {
"id": 1,
"subgroup": "3",
"power": "2",
"grp": "1"
}, {
"id": 1,
"subgroup": "3",
"power": "2",
"grp": "2"
}, {
"id": 1,
"subgroup": "3",
"power": "2",
"grp": "3"
}, {
"id": 1,
"subgroup": "4",
"power": "1",
"grp": "1"
}, {
"id": 1,
"subgroup": "4",
"power": "1",
"grp": "2"
}, {
"id": 1,
"subgroup": "4",
"power": "1",
"grp": "4"
}
}
中已经存在var myObj = {
"id" : id,
"subgroup" : subgroup,
"power" : power,
"grp" : grp
}
的条目的推荐方法是什么。
答案 0 :(得分:0)
解析后的JSON成为对象。
您可以像这样合并对象
ECMAScript 2015(ES6)标准方法
/* For the case in question, you would do: */
Object.assign(obj1, obj2);
/** There's no limit to the number of objects you can merge.
* All objects get merged into the first object.
* Only the object in the first argument is mutated and returned.
* Later properties overwrite earlier properties with the same name. */
const allRules = Object.assign({}, obj1, obj2, obj3, etc);
更多详细说明
访问-How can I merge properties of two JavaScript objects dynamically?