我有一个JSON对象,其中属性有点嵌套。我想在嵌套的JSON列表中插入一个数组,请参阅下面的代码以获取我的JSON对象。
JSON对象:
{
"companyId": 1,
"formation": "c",
"location": [{
"landmark": "Coca Cola",
"street1": "4104 Banner Rd",
"type": "",
"contact": []
}, {
"landmark": "Pepsi",
"street1": "4304 Commercial Rd",
"type": "",
"contact": []
}]
}
要插入的联系数组是:
{
"medium": "Office Phone",
"serviceLocator": "800-285-3000",
"prefered": "true",
"locationRef": "Coca Cola"
}
我想做的就是这样:
在LOCATION中插入CONTACT,其中LOCATION.landmark等于" Coca Cola"
请指导我如何做到这一点,在我的AngularJS控制器中,我想尝试这样的事情,但是没有工作; AngularJS控制器:
$scope.company.location.contact.landmark["coca cola"].push({
"medium": "Office Phone",
"serviceLocator": "800-285-3000",
"prefered": "true",
"locationRef": "Coca Cola"
});
答案 0 :(得分:1)
您可以使用foreach
:
$scope.company.location.forEach(loc => {
if(loc.landmark === 'coca cola') {
loc.contact.push({
"medium": "Office Phone",
"serviceLocator": "800-285-3000",
"prefered": "true",
"locationRef": "Coca Cola"
});
}
});
答案 1 :(得分:1)
遍历位置数组并找到地标值等于“可口可乐”的索引。在该索引处插入联系人
for(var i=0; i<$scope.company.location.length; i++)
{
if($scope.company.location[i].landmark=="Coca cola")
{
$scope.company.location[i].push(contact);
}
}
答案 2 :(得分:-1)
您需要提及数组的索引
myArray.location[0].contact.push(contact);
编辑:
您可以使用 array.find()
然后推送到特定阵列!
<强>样本强>
var myArray = {
"companyId": 1,
"formation": "c",
"location": [{
"landmark": "Coca Cola",
"street1": "4104 Banner Rd",
"type": "",
"contact": []
}, {
"landmark": "Pepsi",
"street1": "4304 Commercial Rd",
"type": "",
"contact": []
}]};
var contact = {
"medium": "Office Phone",
"serviceLocator": "800-285-3000",
"prefered": "true",
"locationRef": "Coca Cola"
};
var result = myArray.location.find(t=>t.landmark ==='Coca Cola');
result.contact.push(contact);
console.log(result);
&#13;