-3

I have the following variable holding a json array.

let requestJson = '{ "data": [ { "type": "Type1", "value": "MyValue" } ] }';

I would like to add a property called "Id" to the above object inside data array. I expect to get something like;

{ "data": [ { "type": "Type1", "value": "MyValue", "id": "123" } ] }

How can I achieve this? I tried the following:

requestJson["data"][0]["id"] = '123';

But when I print requestJson["data"] I'm getting undefined. Would appreciate any help in appending the "Id" attribute to the object inside the array above. Thanks in advance.

AnOldSoul
  • 4,017
  • 12
  • 57
  • 118
  • 6
    requestJson is a string, not an object. Use JSON.parse(requestJson) first (or eliminate the outer single quote marks). Also, you can do `requestObj.data[0].id = '123'` – Andrew Parks Jan 11 '23 at 22:01
  • and of course [Safely turning a JSON string into an object](https://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object) – pilchard Jan 11 '23 at 22:06
  • @pilchard did refer to that question but I was confused since I had to append to the object inside the array, instead of updating the array with a new object. Thanks – AnOldSoul Jan 11 '23 at 22:08
  • @AnOldSoul your access attempt was correct, it was just the parsing that you were missing – pilchard Jan 11 '23 at 22:30

1 Answers1

3

You need to parse your string to convert it to an Object and after that you can manipulate the data attribute

let requestJson = '{ "data": [ { "type": "Type1", "value": "MyValue" } ] }';
const parsedObject = JSON.parse(requestJson)
parsedObject.data[0].id = 1
console.log(parsedObject)
JuanDM
  • 1,250
  • 10
  • 24