Adding a New Array Element to a JSON Object

Adding a new array element to a JSON object

JSON is just a notation; to make the change you want parse it so you can apply the changes to a native JavaScript Object, then stringify back to JSON

var jsonStr = '{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"}]}';

var obj = JSON.parse(jsonStr);
obj['theTeam'].push({"teamId":"4","status":"pending"});
jsonStr = JSON.stringify(obj);
// "{"theTeam":[{"teamId":"1","status":"pending"},{"teamId":"2","status":"member"},{"teamId":"3","status":"member"},{"teamId":"4","status":"pending"}]}"

Adding a new element to an array in the json object java

I would rather go for cleaner approach, create Object with below structure -

public class Response{
private String name;
private int id;
private List<Node> nodes;
<Getter & Setter>
}
public class Node{
private String nodeId;
}
  1. Serialize the json -

Response response = objectMapper.readValue(responseJson,
Response.class);


  1. Add the new incoming node object to response -

response.getNodes().add(New Node("{new node Value}"));


  1. Deserialize before post -

objectMapper.writeValueAsString(response);

How to push JSON object in to array using javascript

Observation

  • If there is a single object and you want to push whole object into an array then no need to iterate the object.

Try this :

var feed = {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"};
var data = [];data.push(feed);
console.log(data);

add new field in every json object in a array javascript

Just loop though array and add

const data = {
"messages": [
{
"msgId": "2021082111010755885",
"interfaceId": 5,
"status": "QUEUED",
"createdAt": "2021-08-21 11:01:07.89554",
"modifiedAt": "2021-08-21 11:01:07.89554",
"count": 0,

},
{
"msgId": "2021082012204615964",
"interfaceId": 5,
"status": "QUEUED",
"createdAt": "2021-08-20 12:20:46.187297",
"modifiedAt": "2021-08-20 12:31:06.622",
"count": 5,

},
{
"msgId": "2021082012204575430",
"interfaceId": 5,
"status": "QUEUED",
"createdAt": "2021-08-20 12:20:46.187297",
"modifiedAt": "2021-08-20 12:27:06.473",
"count": 3,

},
{
"msgId": "2021082012204613152",
"interfaceId": 5,
"status": "QUEUED",
"createdAt": "2021-08-20 12:20:46.187297",
"modifiedAt": "2021-08-20 12:28:06.517",
"count": 3,

}
]
}

data.messages.forEach((node) => node.mString = node.status + "A");

console.log(data);

Add new attribute for the JSON Array List

Just use map:

const data = {
"result": [
{
"id": 210,
"temp": "210",
"city": "colombo",
"status": "waiting"
},
{
"id": 211,
"temp": "212",
"city": "colombo2",
"status": "waiting"
},
]
}

function formatData(data){
return data.result.map(res=> ({...res, select: false}))
}

console.log(formatData(data))


Related Topics



Leave a reply



Submit