I'm working with javascript and JSON. I have a JSON object like this one:
{"firstName":"John", "lastName":"Doe", "id":"1"}
In my case, I have a function like this one:
function addNewValues(jsonArray, firstName, lastName, id)
In case the "firstName" is not a match, I should create a new value in the array.
From
addNewValues({"firstName":"John", "lastName":"Doe", "id":"1"}, "Jane",
"Doe", "2");
it should return:
[
{"firstName":"John", "lastName":"Doe", "id":"1"},
{"firstName":"Jane", "lastName":"Doe", "id":"2"}
]
How can I add this new position?
I tried
myObj.push({"firstName":firstName, "lastName":lastName });
without any success.
Thanks in advance.
JSON.parseyourJSON,pushthe item and thenJSON.stringifyto have aJSON. Or work witharray of objectsandJSON.stringifywhen you have the need ofJSON.push()method, an array has. You should be very careful with what you are doing - having both an array or an object being returned from your function will most probably lead to a mess.