0

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.

2
  • 1
    find the index with array.map(function(x) { return x.ID; }).indexOf(45) Commented May 30, 2018 at 14:16
  • Just for record consider accepting solution which you think helped you. Commented May 31, 2018 at 3:42

3 Answers 3

1

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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;   

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.