合并和匹配与AngularJS匹配的对象

时间:2017-03-06 20:01:06

标签: javascript angularjs json

您好我想合并和匹配两个json对象。我想用Angular方式做。任何帮助将不胜感激。谢谢大家。这是一个例子:


    // First json object
    {
       "UserID":"john.davis",
       "edpi":null,
       "UserApp":[
          {
             "Name":"name3",
             "Link":"/Protect3.php"
          },
          {
             "Name":"name5",
             "Link":"/Admin/Launch.html"
          },
          {
             "Name":"name2",
             "Link":"aaap/defaultBH.php"
          }
       ]
    }

    // Second json object

    [
          {
             "color":"color1",
             "icon": "content/images/icons/administrator.svg",
             "Name": "name5"
          },
          {
             "color":"color3",
             "icon": "content/images/icons/administrator.svg",
             "Name": "name3"
          },
          {
             "color":"color2",
             "icon": "content/images/icons/behavior.svg",
             "Name": "name2"

          }
       ]

希望得到这个


    [
       {
          "TokenName":"name3",
          "TokenLink":"../Protect3.asp",
          "color":{
             "color":"color3",
             "icon": "content/images/icons/administrator.svg",
             "match": "name3"
          }
       },
       {
           "Name":"name5",
             "Link":"/Admin/Launch.html",
          "color":{
              "color":"color1",
             "icon": "content/images/icons/administrator.svg",
             "match": "name5"
          }
       },
       {
             "Name":"name2",
             "Link":"aaap/defaultBH.php"
          "color":{
             "color":"color2",
             "icon": "content/images/icons/behavior.svg",
             "match": "name2"
          }
       }
    ]

1 个答案:

答案 0 :(得分:0)

我明白了。这是下面的代码。


    function mergeArraysOnProperty(array1, array2, property) {
      array1.forEach(function(element1) {
        array2.forEach(function(element2) {
          if (element1[property] === element2[property]) {
            for (var newProperty in element2) {
              if (element2.hasOwnProperty(newProperty)) {
                element1[newProperty] = element2[newProperty];
              }
            }
          }
        });
      });
      return array1;
    };

    $scope.newjson = mergeArraysOnProperty(userapp, color, "Name");

    console.log($scope.newjson);