合并具有相同id的多个json

时间:2017-12-11 09:38:24

标签: javascript angularjs json angularjs-scope

第一个json来自API,通过进行http调用来获取此数据

[
    {
        "clientid": 1,
        "clientname": "facebook",
        "forecasted": 18,
    },
    {
        "clientid": 2,
        "clientname": "youtube",
        "forecasted": 83,
    }
]

我创建第二个json来更新第一个json上的图像

 [
        {
            "clientid": 1,
            "clientname": "facebook ",
            "img":"images/21747.jpg"
        },
        {
            "clientid": 2,
            "clientname": "youtube",
            "img": "images/youtube.svg"
        },
    ]

现在我需要将两个json基于相同的id,并填充第一个json,我来自api与第二个json的图像

app.factory('myFactory', function($http){
  return{

    client: function(callback){
        $http({
          method: "GET",
          url: "http://www.erek.co.za/api/..",
          cache:true
        }).then(callback);
    },  
    list: function(callback){
        $http({
          method: "GET",
          url: "data/Client.json",
          cache:true
        }).then(callback);
    } 
  };
});
app.controller('myController', function ($scope, myFactory) {
          myFactory.client(function(response){
              var data = response.data;
              $scope.myClients = data;
          })
          myFactory.list(function (response) {
            var data = response.data;
            $scope.dark = data;
          })
        });

HTML

<div ng-repeat="client in myClients>
<a href="#{{client.clientid}}" 
  <div class="client-project-panel">
      <div class="client-logo-container">
          <div class="client-logo" >
              <img ng-src="{{dark[$index].img}}" alt="{{client.clientname}}">
           </div>
          <div class="project-forecasted">
             <h2 class="forecasted-value">{{client.forecasted}}%</h2>
             <p>Complete</p>
          </div>
      </div>
  </div>
</a>

2 个答案:

答案 0 :(得分:3)

您可以使用Object.assign方法。

let array1=[ { "clientid": 1, "clientname": "facebook", "forecasted": 18, }, { "clientid": 2, "clientname": "youtube", "forecasted": 83, } ]
let array2 = [ { "clientid": 1, "clientname": "facebook ", "img":"images/21747.jpg" }, { "clientid": 2, "clientname": "youtube", "img": "images/youtube.svg" } ]
 
var expected = array1.map(a => Object.assign(a, array2.find(b => b.clientid == a.clientid)));
console.log(expected);

答案 1 :(得分:1)

myFactory.client(function(response){
          var data = response.data;
          var clientsData = data;
          // after you fetch the clients get list of images
          myFactory.list(function (response) {
            var data = response.data;
            var clientImages = {}
            for(var i=0;i<data.length;i++){
                clientImages[data[i].clientid] = data[i].img
            }
            $scope.dark = clientImages
            $scope.myClients = clientsData
          })

})

在模板中,请参阅{{dark[client.clientid]}}

您可能希望将html包装在ng-if="myClients"中,以便仅在获取数据后显示内容