1

I am trying to add key value pair in the below JSON object, but it is getting added in the wrong way, is there any way i can add to each object a new key value pair, that will help me to complete the req.

JSON as follow :

var object =[
      {
         "asdf":"",
         "fdrtf":"869966",
         "hdhfhfh":"utytut",
         "Cat":"A"
         
      },
      {
         "hjhj":"",
         "hfhfhf":"h",
         "hhfh":"hfjfhdj",
         "cat":"B"
         
      },
      {
         "hjhj":"",
         "hfhfhf":"h",
         "hhfh":"hfjfhdj",
         "cat":"B"
      }
]

code i am using to add the new key value pair :
for (let i = 0; i < object.length; i++) {
            object[i]['ABC'] = [i];
        }

Actually expected should be:

var object =[
      {
         "asdf":"",
         "fdrtf":"869966",
         "hdhfhfh":"utytut",
         "Cat":"A",
         "ABC": "0"
         
      },
      {
         "hjhj":"",
         "hfhfhf":"h",
         "hhfh":"hfjfhdj",
         "cat":"B",
         "ABC": "1"
         
      },
      {
         "hjhj":"",
         "hfhfhf":"h",
         "hhfh":"hfjfhdj",
         "cat":"B"
         "ABC": "2"
      }
]

the final value i am getting as below:

["0":{
         "hjhj":"",
         "hfhfhf":"h",
         "hhfh":"hfjfhdj",
         "cat":"B",
      
   },
   "1":{
         "asdf":"",
         "fdrtf":"869966",
         "hdhfhfh":"utytut",
         "Cat":"A"
         
   },
   "2":{
       "hjhj":"",
         "hfhfhf":"h",
         "hhfh":"hfjfhdj",
         "cat":"B"
   }
  ]

kindly someone help me out to get the expected value,,,really need it

1 Answers1

2

The code which you have pasted looks ok. but you are assigning the array to ABC property.

Remove the array and just assign the value.

for (let i = 0; i < object.length; i++) {
        object[i]['ABC'] = i
}

working example:

var object = [
    {
        "asdf": "",
        "fdrtf": "869966",
        "hdhfhfh": "utytut",
        "Cat": "A"

    },
    {
        "hjhj": "",
        "hfhfhf": "h",
        "hhfh": "hfjfhdj",
        "cat": "B"

    },
    {
        "hjhj": "",
        "hfhfhf": "h",
        "hhfh": "hfjfhdj",
        "cat": "B"
    }
]

for (let i = 0; i < object.length; i++) {
    object[i]['ABC'] = i
}

console.log(object);

//Use JSON.stringify if you need Json string
console.log(JSON.stringify(object));

Using ES6 map and spread operator

var object = [
    {
        "asdf": "",
        "fdrtf": "869966",
        "hdhfhfh": "utytut",
        "Cat": "A"

    },
    {
        "hjhj": "",
        "hfhfhf": "h",
        "hhfh": "hfjfhdj",
        "cat": "B"

    },
    {
        "hjhj": "",
        "hfhfhf": "h",
        "hhfh": "hfjfhdj",
        "cat": "B"
    }
]

let updatedObject = object.map( (item, index) => ({...item, 'ABC': index}));
console.log(updatedObject);

//Use JSON.stringify if you need Json string
console.log(JSON.stringify(updatedObject));
Sohail Ashraf
  • 10,078
  • 2
  • 26
  • 42