-1

Hi I have a requirement in which i need to add a new key value pair in the JSON response, with the help of the for loop, kindly help me out for this

below is my JSON:

[
      {
         "asdf":"",
         "fdrtf":"869966",
         "hdhfhfh":"utytut",
         "Cat":"A",
         "hghg":"jguyhj",
         "hfj":"Resolved",
         "hghgjg":"",
         "hgfjf":"",
         "jghjf":"",
         "hgjfhfj":"",
         "contraName":""
      },
      {
         "hjhj":"",
         "hfhfhf":"h",
         "hhfh":"hfjfhdj",
         "cat":"B",
         "jghgj":"jhgjgk",
         "hgjfjf":"jghjg",
         "hgjgugj":"",
         "jghfj":"",
         "jghgj":"",
         "gjghfj":"",
         "hgjgh":""
      }
    ] 

i am trying to add a new key value pair like : -- "ASD":"1" in the first row and "ASD":"2" in the second row by the help of for loop in my jS file ,, kindly help me out for this.

below is the method i tried:

addvalue(data) {
        for (let i = 0; i < data.length; i++) {
           data[i].ASD = `[i]`;
        }
        
    }
0
1

I would use Object.assign.

see code

const data = [{ a: 1, b: 2 }, { b: 4, c: 5 }];
const data2 = {ASD:10};

for (let i = 0; i < data.length; i++) {
  data[i] = Object.assign(data[i], data2);
}

console.log(data);

See link.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Not the answer you're looking for? Browse other questions tagged or ask your own question.