Javascript 如何通过AngularJS控制器在嵌套的JSON属性中插入数组

Javascript 如何通过AngularJS控制器在嵌套的JSON属性中插入数组,javascript,angularjs,json,Javascript,Angularjs,Json,我有一个JSON对象,其中的属性有点嵌套。我想在嵌套的JSON列表中插入一个数组,请参阅下面我的JSON对象的代码 JSON对象: { "companyId": 1, "formation": "c", "location": [{ "landmark": "Coca Cola", "street1": "4104 Banner Rd", "type": "", "contact": [] }, { "landmark": "Pepsi", "st

我有一个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": []
}]
$scope.company.location.contact.landmark["coca cola"].push({

    "medium": "Office Phone",
    "serviceLocator": "800-285-3000",
    "prefered": "true",
    "locationRef": "Coca Cola"

});
}

联系人要插入的数组是:

{
    "medium": "Office Phone",
    "serviceLocator": "800-285-3000",
    "prefered": "true",
    "locationRef": "Coca Cola"
}
我想做的就是这样:

在LOCATION.landmark等于“可口可乐”的位置插入联系人

请指导我如何做到这一点,在我的AngularJS控制器中,我正在考虑尝试类似的东西,但不起作用; AngularJS控制器:

{
"companyId": 1,
"formation": "c",
"location": [{
    "landmark": "Coca Cola",
    "street1": "4104 Banner Rd",
    "type": "",
    "contact": []
}, {
    "landmark": "Pepsi",
    "street1": "4304 Commercial Rd",
    "type": "",
    "contact": []
}]
$scope.company.location.contact.landmark["coca cola"].push({

    "medium": "Office Phone",
    "serviceLocator": "800-285-3000",
    "prefered": "true",
    "locationRef": "Coca Cola"

});

您需要提到数组的索引

myArray.location[0].contact.push(contact);
编辑:

您可以使用
array.find()
然后推送到特定的数组

演示

var myArray={
“公司ID”:1,
“形成”:“c”,
“地点”:[{
“里程碑”:“可口可乐”,
“街道1”:“班纳路4104号”,
“类型”:“,
“联系人”:[]
}, {
“里程碑”:“百事可乐”,
“一号街”:“商业路4304号”,
“类型”:“,
“联系人”:[]
}]};
var触点={
“中等”:“办公电话”,
“serviceLocator”:“800-285-3000”,
“首选”:“正确”,
“locationRef”:“可口可乐”
};
var result=myArray.location.find(t=>t.landmark==='Coca-Cola');
结果.接触.推(接触);

控制台日志(结果)您可以通过使用
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"
        });
    }
});

遍历location数组,找到landmark值等于“Coca-Cola”的索引。在该索引处插入联系人

for(var i=0; i<$scope.company.location.length; i++)
{
   if($scope.company.location[i].landmark=="Coca cola")
   {
      $scope.company.location[i].push(contact);
   }
}

for(var i=0;iI)不想提及索引,因为我不知道哪个索引上有“Coca-Cola”,但我想找到地标并在该位置插入联系人
find
只返回第一个匹配项。@ChrisRiebschlager OP没有提到该要求,他可以使用filter()