【问题标题】:Using JavaScript combine Two JSON objects by matching key value and index value使用 JavaScript 通过匹配键值和索引值组合两个 JSON 对象
【发布时间】:2017-11-13 01:46:49
【问题描述】:

好的,我一直在绞尽脑汁尝试各种方法,但总是遇到死胡同。我什至尝试使用 Angular 进行嵌套 ng-repeats 以过滤到我需要的属性,但这对资源来说太重了。

我要做的是查找“groups”数组中每个对象的“indices”值,并通过将索引与“indices”值匹配来在“person”数组中找到相应的对象,然后将该值推送到“组”数组中的相应对象。

当从 api 返回响应时,我试图仅在 JavaScript 中执行此操作。

下面的例子:

    var obj = {
    "groups": [
        {
          "name": "GroupA",
          "indices": [
            0
          ]
        },
        {
          "name": "GroupB",
          "indices": [
            1
          ]
        },
        {
          "name": "GroupC",
          "indices": [
            2,
            3
          ]
        }
      ],
    "person": [
        {"name": "Archer"},
        {"name": "Lana"},
        {"name": "Mother"},
        {"name": "Barry"}
      ]
  };

这就是我希望最终对象的样子:

 var obj = {
    "groups": [
        {
          "name": "GroupA",
          "indices": [
            0
          ],
        "person": [
          {"name": "Archer"}
          ]
        },
        {
          "name": "GroupB",
          "indices": [
            1
          ],
          "person": [
            {"name": "Lana"}
          ]
        },
        {
          "name": "GroupC",
          "indices": [
            2,
            3
          ],
          "person": [
            {"name": "Mother"},
            {"name": "Barry"}
          ]
        }
      ]
  };

【问题讨论】:

    标签: javascript arrays angularjs json


    【解决方案1】:

    我会在外部循环中使用 forEach 而不是 map,但这更多的是风格问题:

     obj.groups.forEach(g => g.person = g.indices.map(i => obj.person[i]))
    

    var obj = {
        "groups": [
            {
              "name": "GroupA",
              "indices": [0]
            },
            {
              "name": "GroupB",
              "indices": [ 1 ]
            },
            {
              "name": "GroupC",
              "indices": [2,3 ]
            }
          ],
        "person": [
            {"name": "Archer"},
            {"name": "Lana"},
            {"name": "Mother"},
            {"name": "Barry"}
          ]
      };
    
      obj.groups.forEach(g =>  g.person = g.indices.map(i => obj.person[i]))
      console.log(obj.groups)

    【讨论】:

    • 这会改变输入。可能是也可能不是问题,但map 从来都不是问题。
    • @JohanP 是的,确实如此。这就是我阅读问题的方式:'然后将该值推送到'groups'数组中的相应对象。'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    • 2018-07-13
    相关资源
    最近更新 更多