如何将值推入对象内部的数组

时间:2020-03-21 07:06:09

标签: javascript angular typescript

我在对象内部有一个看起来像这样的数组。

sourceSystemArray = [{
  "attId" : 2257,
  "attributeName" : "country",
  "attributeValues" : [ "AU", "KG", "IN", "AF" ]
}]

使用输入字段,我为用户提供了添加新值的选项。 现在,我想最后将使用ngModel获得的New Input值添加到attributeValues数组。 因此,假设用户输入一个新的国家/地区,例如NZ。 所以我想将NZ推送到attributeValues,我的最终Object应该是这样的:

sourceSystemArray = [{
      "attId" : 2257,
      "attributeName" : "country",
      "attributeValues" : [ "AU", "KG", "IN", "AF","NZ" ]
    }]

我尝试使用push方法,但是没有用。 有人可以帮我弄清楚如何实现它。

3 个答案:

答案 0 :(得分:1)

如果您要添加此对象,则可能会遇到问题,因为它本身在数组中。这就是我要添加到attributeValues的方法。

let myarray = [{
  "attId" : 2257,
  "attributeName" : "country",
  "attributeValues" : [ "AU", "KG", "IN", "AF" ]
}]

myarray[0].attribute values.push('GB')

或者,假设它不是数组中的唯一项。

let myarray = [{
  "attId" : 2257,
  "attributeName" : "country",
  "attributeValues" : [ "AU", "KG", "IN", "AF" ]
}]

myarray.find(item => item.attId === 2257)
  .attributeValues.push('GB')

答案 1 :(得分:0)

由于sourceSystemArray是一个数组,因此请尝试

sourceSystemArra[0].attributeValues.push("NZ");

答案 2 :(得分:0)

在html部分中,您应该同时发送attId和具有功能的新值

然后在组件u中应找到具有attId的方法

function(attId,newValue){    
    this.sourceSystemArray.find(data=>data.attId ==attId).attributeValues.push(newValue);  
}