-2

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.

4
  • 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' Commented Jan 11, 2023 at 22:01
  • and of course Safely turning a JSON string into an object Commented Jan 11, 2023 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 Commented Jan 11, 2023 at 22:08
  • @AnOldSoul your access attempt was correct, it was just the parsing that you were missing Commented Jan 11, 2023 at 22:30

1 Answer 1

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)

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.