Cpt Kitkat
Cpt Kitkat

Reputation: 1402

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. So suppose user enters a new Country say NZ. So I want to push NZ to attributeValues and my final Object should like this:

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.

Upvotes: 0

Views: 142

Answers (3)

cd3k
cd3k

Reputation: 812

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.

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')

Upvotes: 1

Cagri Tacyildiz
Cagri Tacyildiz

Reputation: 17610

in html part u should send both attId and your new value with function

then in component u should find method with attId

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

Upvotes: 0

azer-p
azer-p

Reputation: 282

Since sourceSystemArray is an array, try this

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

Upvotes: 0

Related Questions