简体   繁体   English

如何将值推送到对象内的数组

[英]How to Push Value to an Array Inside an Object

I have an array inside an Object which looks like this.我在一个对象中有一个数组,它看起来像这样。

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

Using input field I give user option to add a new Value.使用输入字段,我为用户提供添加新值的选项。 Now I would like to finally add the New Input value that I get using ngModel to attributeValues array.现在我想最终将使用ngModel获得的新输入值添加到 attributeValues 数组。 So suppose user enters a new Country say NZ.所以假设用户输入一个新的国家,比如 NZ。 So I want to push NZ to attributeValues and my final Object should like this:所以我想将 NZ 推到 attributeValues 并且我的最终对象应该是这样的:

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

I tried using push method but it's not working.我尝试使用推送方法,但它不起作用。 Can someone help me figure out how to achieve it.有人可以帮我弄清楚如何实现它。

If you're trying to add this object you might be having problems because it's in an array itself.如果您尝试添加此对象,您可能会遇到问题,因为它本身就在一个数组中。 Here's how I would add to attributeValues .这是我添加到attributeValues

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

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

Or, assuming it's not the only item in the array.或者,假设它不是数组中唯一的项目。

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

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

由于sourceSystemArray是一个数组,试试这个

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

in html part u should send both attId and your new value with function在 html 部分,您应该使用函数发送 attId 和新值

then in component u should find method with attId然后在组件中你应该找到带有 attId 的方法

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

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

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