Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append JSON data to existing array of objects in Node.js [duplicate]

Consider I have an array

let array1 = [{a:1, b:2}, {e:5,f:6}]
let json1 = {c:3, d:4}

I want to append json1 to first item of array1 so the resultant looks like

array1 = [{a:1, b:2, c:3, d:4}, {e:5, f:6}]

I am sure push doesn't work here. I am not sure how to proceed further.

like image 645
user1852574 Avatar asked Mar 31 '20 16:03

user1852574


People also ask

How JSON file append data in node JS?

Append file creates file if does not exist. But ,if you want to append JSON data first you read the data and after that you could overwrite that data. We have to read the data, parse, append, and then overwrite the original file because of the JSON format.

How do I add a JSON object to an existing JSON array in node JS?

Use push() method to add JSON object to existing JSON array in JavaScript. Just do it with proper array of objects .

How do I add to an existing JSON file?

Steps for Appending to a JSON FileRead the JSON in Python dict or list object. Append the JSON to dict (or list ) object by modifying it. Write the updated dict (or list ) object into the original file.

Can JSON containing multiple objects?

The file is invalid if it contains more than one JSON object. When you try to load and parse a JSON file with multiple JSON objects, each line contains valid JSON, but as a whole, it is not a valid JSON as there is no top-level list or object definition.


1 Answers

You can use spread operator

let array1 = [{a:1, b:2}, {e:5,f:6}];
let json1 = {c:3, d:4};
array1[0] = {...array1[0], ...json1};
console.log(array1);
like image 94
Nikhil Aggarwal Avatar answered Sep 20 '22 19:09

Nikhil Aggarwal