What is the best way to add an array of JSON objects to another array of JSON objects?

The current JSON array obtained from the response is as follows:

comments:[{id: "3124fac5-9d3e-4fa9-8a80-10f626fbf141", createdDate: 1469606019000,…},…]
0:{id: "3124fac5-9d3e-4fa9-8a80-10f626fbf141", createdDate: 1469606019000,…}
createdBy:{id: "cf2829b7-0c76-4a08-9562-ccbfa012ef2d", createdDate: 1469605771000, name: "user",…}
createdDate:1469606019000
id:"3124fac5-9d3e-4fa9-8a80-10f626fbf141"
lastModifiedBy:{id: "cf2829b7-0c76-4a08-9562-ccbfa012ef2d", createdDate: 1469605771000, name: "user",…}
lastModifiedDate:1469606019000
message:"twrey"
1:{id: "350fd2bd-f452-495c-9bd5-79aa7c799d02", createdDate: 1469619161000,…}
createdBy:{id: "cf2829b7-0c76-4a08-9562-ccbfa012ef2d", createdDate: 1469605771000, name: "user",…}
createdDate:1469619161000
id:"350fd2bd-f452-495c-9bd5-79aa7c799d02"
lastModifiedBy:{id: "cf2829b7-0c76-4a08-9562-ccbfa012ef2d", createdDate: 1469605771000, name: "user",…}
lastModifiedDate:1469619161000
message:"yuo"

I intend to add a new files array of JSON to the existing comments array of JSON. The resulting JSON should appear like this:

comments:[{id: "3124fac5-9d3e-4fa9-8a80-10f626fbf141", createdDate: 1469606019000,…},…]
0:{id: "3124fac5-9d3e-4fa9-8a80-10f626fbf141", createdDate: 1469606019000,…}
createdBy:{id: "cf2829b7-0c76-4a08-9562-ccbfa012ef2d", createdDate: 1469605771000, name: "user",…}
createdDate:1469606019000
id:"3124fac5-9d3e-4fa9-8a80-10f626fbf141"
lastModifiedBy:{id: "cf2829b7-0c76-4a08-9562-ccbfa012ef2d", createdDate: 1469605771000, name: "user",…}
lastModifiedDate:1469606019000
message:"twrey"
files:[]
1:{id: "350fd2bd-f452-495c-9bd5-79aa7c799d02", createdDate: 1469619161000,…}
createdBy:{id: "cf2829b7-0c76-4a08-9562-ccbfa012ef2d", createdDate: 1469605771000, name: "user",…}
createdDate:1469619161000
id:"350fd2bd-f452-495c-9bd5-79aa7c799d02"
lastModifiedBy:{id: "cf2829b7-0c76-4a08-9562-ccbfa012ef2d", createdDate: 1469605771000, name: "user",…}
lastModifiedDate:1469619161000
message:"yuo"
files:[]

Answer №1

If you are looking to combine two arrays of objects, a good approach would be using Array.map() along with Object.assign().

It is important to note that the two arrays must have the same length for this method to work effectively.

var x = [{id: 1, asd: 2}, {id: 2, asd: 3}];
var y = [{files: 'asd'}, {files: 'dsa'}];

var z = x.map((object, index) => Object.assign(object, y[index]));

console.log(z)

Answer №2

To add a new property to jsonObject, simply write the following code. You just need to understand how to Add new attribute (element) to JSON object using JavaScript

yourCurrentJSONObject.propertyNameToAdd = yourFilesArray;

For example:

var yourCurrentJSONObject = {
comments:[{id: "3124fac5-9d3e-4fa9-8a80-10f626fbf141", createdDate: 1469606019000,…},…]
0:{id: "3124fac5-9d3e-4fa9-8a80-10f626fbf141", createdDate: 1469606019000,…}
createdBy:{id: "cf2829b7-0c76-4a08-9562-ccbfa012ef2d", createdDate: 1469605771000, name: "user",…}
createdDate:1469606019000
id:"3124fac5-9d3e-4fa9-8a80-10f626fbf141"
lastModifiedBy:{id: "cf2829b7-0c76-4a08-9562-ccbfa012ef2d", createdDate: 1469605771000, name: "user",…}
lastModifiedDate:1469606019000
message:"twrey"
1:{id: "350fd2bd-f452-495c-9bd5-79aa7c799d02", createdDate: 1469619161000,…}
createdBy:{id: "cf2829b7-0c76-4a08-9562-ccbfa012ef2d", createdDate: 1469605771000, name: "user",…}
createdDate:1469619161000
id:"350fd2bd-f452-495c-9bd5-79aa7c799d02"
lastModifiedBy:{id: "cf2829b7-0c76-4a08-9562-ccbfa012ef2d", createdDate: 1469605771000, name: "user",…}
lastModifiedDate:1469619161000
message:"yuo"
}

var yourFilesArray = [....];
yourCurrentJSONObject['files'] = yourFilesArray;
//    or simply
yourCurrentJSONObject.files = yourFilesArray;    

After executing the above instruction and checking the console, you will see that the files array is now included along with comments and messages.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular - Switching Displayed Information

I am currently working with Angular 4 and I am attempting to switch between contenteditable="true" and contenteditable="false" Here is what I have so far: <h1 (dblclick)="edit($event)" contentEditable="true">Double-click Here to edit</h1> Al ...

Declaring a function within a conditional statement

I recently came across a code sample in the book You Don't Know JS: Scope & Closures that is puzzling to me. "Function declarations that appear inside of normal blocks typically hoist to the enclosing scope, rather than being conditional as this ...

Encountered a problem when attempting to upload images to Cloudinary through the front-end and save the information in a MySQL database using Axios on Node JS

I am currently working on a web application using React. I have implemented a form where users can input text data and upload multiple image files. The goal is to store the submitted images on Cloudinary along with other text data in a MySQL database. Unf ...

The functionality of socket.io is not functioning properly on the server, resulting in a 404

I encountered errors while working on a simple socket.io project on my server. The IP address I am using is . All files are stored in public_html and can be accessed through the URL: . Here are the code snippets: <!doctype html> <html> < ...

"Exploring the process of looping through an array of JavaScript objects and showcasing a List Selector on the Google Assistant app with the help of

After extensively researching all the available documentation at https://developers.google.com/actions/assistant/responses In the documentation for the "List Selector," all the examples provided involve static and predetermined data. In a real-world scen ...

Issue with dynamic imports in express routes

I am currently attempting to incorporate a dynamic import within an express.js router Here is the code snippet I have: HelloWorldController.js export const helloWorld = function (req, res) { res.send('hello world') } router.js export defa ...

Leverage jQuery to automatically submit an ajax form once all ajax requests have been successfully executed

I have integrated a WordPress plugin for store locator on my website. For pages without the interactive map, I have set up a form that serves as a location search tool. To clarify, the form includes a location field where users can input their desired loc ...

Is it possible to turn off Angular CLI ng build linting for a specific directory?

I am facing an issue with a specific directory in my project template that I want to exclude from linting. Despite excluding it in both tsconfig and eslint, running eslint works fine but when using ng build, the directory is still included in linting and e ...

Using data variables as arguments in the style section of Vue2

Suppose we have a data variable and I want to utilize this data variable for styling purposes. data() { return{ selected:{ index: 2 } } } <style> .parent-table >>> .table-row:nth-child(/* here I intend to use ...

Using event source with a non-default JSON format: A step-by-step guide

I am currently using FullCalendar with an event source that does not provide the JSON format required by FullCalendar. The events are located "one level down" from where they should be in the JSON structure. For instance, the JSON returned by the feed mig ...

Is there a way to send an array of objects using axios-http?

Currently, I am utilizing react-dropzone for uploading mp3 files and a metadata npm to extract all the file contents. However, upon sending it to axios.post(), an error is encountered stating "Body Exceeded 1mb limit" Here is the snippet where the new dat ...

Implement multiple selection of parameters in React Material UI version 1.0 and handle the onChange

Currently, I am working on implementing React Material UI 1.0.0-beta.34 and encountering an issue with the Select component. My challenge lies in trying to include an extra parameter in the onChange event handler, yet it seems that only the event parameter ...

Utilizing an Ajax call within "for" loops can result in skipping either odd or even iterations

Seeking assistance because we are facing a challenge that we cannot seem to overcome. Despite researching on platforms like StackOverflow and search engines, implementing a solution or solving the problem remains elusive. The goal is to develop a JavaScri ...

Error when making a POST request: Unexpected JSON token 'o' at position 1

My situation involves trying to retrieve the JSON request body for a POST request using node and express. Unfortunately, I'm encountering an error message from express: SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<anony ...

Exploring the capabilities of IBM Integration Bus in handling JSON parsing operations

Hello, I am currently facing an issue with parsing JSON data in the IIB Toolkit. The error message thrown by the java compute node is: "java.lang.NoClassDefFoundError: org.json.JSONObject" When attempting to parse incoming JSON messages using UTF-8 encodi ...

JSONSchema - issue with mandatory properties not functioning correctly

I've recently delved into JSON and it seems like I might have overlooked something quite simple. Despite my efforts, I can't figure out what's causing my schema to incorrectly validate certain elements. This is the schema I am working with: ...

What is the process for modifying a Date type value in JavaScript?

I'm looking to create a graph that illustrates the sun's altitude throughout the day, resembling a sine curve. Users should be able to input a location (latitude & longitude) and a date, and the graph will adjust accordingly. I've incorpora ...

The reason behind the successful execution of the final .then in promise chaining

I am new to JavaScript and have encountered an interesting problem with the following code. Even though I haven't returned anything from the .then method, the last .then (blue color) works instead of the first one (red color). Can someone explain why ...

working with html data in a bootstrap modal using javascript

Utilizing an id, I pass data to a bootstrap modal and link that id with stored data. $("#fruit").html($(this).data("fruit")); In addition, I am appending data to the bootstrap modal $('#mymodal').find('.modal-body').append('< ...

What is causing the warnings for a functional TypeScript multidimensional array?

I have an array of individuals stored in a nested associative array structure. Each individual is assigned to a specific location, and each location is associated with a particular timezone. Here is how I have defined my variables: interface AssociativeArr ...