繁体   English   中英

如何将数组推送到仅匹配父属性的嵌套子对象?

[英]How to push array to nested child object of only matching parent properties?

以下是我的JSON结构:

$scope.dataList = [{
   CompanyName: null,
   Location: null,
   Client: {
      ClientId: 0,
      ClientName: null,
      Projects:{
         Id: 0,
         Name: null,
      }
   }
}];

我在dataList范围变量中有此数据:

[{
   CompanyName: XXXX,
   Location: California,
   Client:{
      ClientId: 1,
      ClientName: John Cena,
      Projects:{
         Id: 1,
         Name: Abc,
         }
      }
}]

现在,在上面的记录中,我需要按公司名称和位置查找并将Client数组添加到匹配的公司。

现在基于按钮单击事件,我从http调用中获得1条或多条其他记录,如下所示:

[{
   CompanyName: XXXX,
   Location: California,
   Client:[{
      ClientId: 2,
      ClientName: Undertaker,
      Projects:{
         Id: 2,
         Name: Pqr,
      }
   }]
}]

现在,我想将此新客户数据附加到公司XXXX和加利福尼亚位置的dataList对象中。

这是我正在尝试的方法,但出现错误:

$http.get("Url")
    .then(function(data) {
        for (var i = 0; i < data.length; i++) // when there will be more than 1 records in response i get from http call
                {
                        var result = $.grep($scope.dataList, function (e) 
                        {
                            //find records from dataList by Company name and Location
                            return (e.CompanyName == data[i].CompanyName) && (e.Location == data[i].Location);
                        });
                        //Push client Id 2 record in dataList
                        result.Client.push(data[i]);// error:result.Client is undefined
                        console.log(result);
                }
    });

在推送到result.Client之前,您可以使用检查并将Client的内容移动到数组中。

if (!Array.isArray(result.Client)) { // check if not an array
    result.Client = [result.Client]; // create one with the actual content
}
result.Client.push(data[i]);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM