Let's say we have a string containing in array in JSON format:
let json = '[1, 2, 3, 4, 5]';
Let's add one more element to the end of this array. For this we need to take a number of steps.
First, we unpack the JSON into a JavaScript array:
let arr = JSON.parse(json);
Add a new element to the array:
arr.push(6);
And convert the modified array back to JSON:
let res = JSON.stringify(arr);
The final code will look like this:
let json = '[1, 2, 3, 4, 5]';
let arr = JSON.parse(json);
arr.push(6);
let res = JSON.stringify(arr);
console.log(res);
The following JSON is given:
let json = '["user1","user2","user3","user4","user5"]';
Add another user to the end of the string.
The following JSON is given:
let json = '["user1","user2","user3","user4","user5"]';
Change the second user's name.
The following JSON is given:
let json = `[
{
"name": "user1",
"age": 25,
"salary": 1000
},
{
"name": "user2",
"age": 26,
"salary": 2000
},
{
"name": "user3",
"age": 27,
"salary": 3000
}
]`;
Add one more employee to this string.