[英]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.