WhoAmI
WhoAmI

Reputation: 317

Adding key in an array by finding a value AngularJS

I am trying to add an extra key in a JSON array by searching any key value.

Example JSON:-

[
  {
    "$id": "2025",
    "ID": 41,
    "Name": "APPLE"
  },
  {
    "$id": "2026",
    "ID": 45,
    "Name": "MANGO"
  },
  {
    "$id": "2027",
    "ID": 48,
    "Name": "GUAVA"
  }
]

Suppose I have to add a new key pair example "Price": 50 after "Name": "MANGO" or by finding ID ID": 45. So my expected new JSON will be :-

[
  {
    "$id": "2025",
    "ID": 41,
    "Name": "APPLE"
  },
  {
    "$id": "2026",
    "ID": 45,
    "Name": "MANGO",
    "Price": 50
  },
  {
    "$id": "2027",
    "ID": 48,
    "Name": "GUAVA"
  }
]

It must add on the object related to matched search key.

So, I am not able to find out any function related to the issue.

Upvotes: 0

Views: 553

Answers (3)

Lokesh Pandey
Lokesh Pandey

Reputation: 1789

You can run a loop and check the condition and then add a property to an object. Here is a running code snippet. You can read here more about JavaScript Objects

var myarray = [
                {
                    "$id": "2025",
                    "ID": 41,
                    "Name": "APPLE"
                },
                {
                    "$id": "2026",
                    "ID": 45,
                    "Name": "MANGO"
                },
                {
                    "$id": "2027",
                    "ID": 48,
                    "Name": "GUAVA"     
                }
]
for(var i=0;i<myarray.length;i++){
  if(myarray[i].$id === "2025" || myarray[i].Name === "APPLE"){
    var data = myarray[i];
    data.price = 50
  }
}
console.log(myarray)

Upvotes: 1

Hassan Imam
Hassan Imam

Reputation: 22524

You can use array#find to compare the ID. Then based that you can add Price key to the object.

let arr = [ { "$id": "2025", "ID": 41, "Name": "APPLE" }, { "$id": "2026", "ID": 45, "Name": "MANGO" }, { "$id": "2027", "ID": 48, "Name": "GUAVA" } ],
    id = 45,
    obj = arr.find(({ID}) => ID === id);
if(obj);
  obj.Price = 50;
console.log(arr);

Upvotes: 1

hsz
hsz

Reputation: 152206

You can try with:

data.find(item => item.ID === 45).price = 50;

To cover the case if item is not available:

(data.find(item => item.ID === 45) || {}).price = 50;   

Upvotes: 0

Related Questions