合并JavaScript中的两个对象

时间:2018-07-02 16:36:15

标签: javascript

我有两个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 4grp 4中(调查JSON B)。我想将JSON B中的每个grp 3添加到JSON A中的每个subgroup中(除了grp中已经存在这些grp的地方。像JSON A中一样包含subgroupsubgroup 3的条目,我们将跳过该条目。) grp 4Id的值将分别相似。因此,我们要在power中添加subgroup 3并在grp 1, 2, 3中添加subgroup 4。对于group 1, 2, 4subgroup 3power的值分别为id,对于2, 1subgroup 4power的值分别为{ {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 } 的条目的推荐方法是什么。

1 个答案:

答案 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?