Combining two arrays of objects using JavaScript

I am working with two arrays of objects that look like this:

objects [ { countMedias: 2 },
  { countMedias: 1 },
  { countMedias: 3 },
  { countMedias: 1 },
  { countMedias: 2 } ]
listePlayliste [ { nom_playlist: 'bbbb' },
  { nom_playlist: 'ccc' },
  { nom_playlist: 'aaaa' },
  { nom_playlist: 'xxxx' },
  { nom_playlist: 'resttttttttt' } ]

My goal is to merge both arrays to create a new array structured as follows:

Result [ { nom_playlist: 'bbbb', countMedias: 2 },
  { nom_playlist: 'ccc', countMedias: 1  },
  { nom_playlist: 'aaaa', countMedias: 3 },
  { nom_playlist: 'xxxx', countMedias: 1 },
  { nom_playlist: 'resttttttttt', countMedias: 2 } ]

I attempted the following approach, but it did not yield the desired result:

Array.prototype.push.apply(json,objects); 

Answer №1

Consider trying the following code snippet:

objects.map((object, index) => Object.assign(object, listePlayliste[index]))

This method may be effective for small arrays, but avoid using it on larger ones as it could lead to decreased performance.

Answer №2

Try using the map method to iterate over one array and return an object that combines elements from two arrays based on their index.

const objects = [{
    countMedias: 2
  },
  {
    countMedias: 1
  },
  {
    countMedias: 3
  },
  {
    countMedias: 1
  },
  {
    countMedias: 2
  }
];

const listePlayliste = [{
    nom_playlist: 'bbbb'
  },
  {
    nom_playlist: 'ccc'
  },
  {
    nom_playlist: 'aaaa'
  },
  {
    nom_playlist: 'xxxx'
  },
  {
    nom_playlist: 'resttttttttt'
  }
];

const output = objects.map((obj, i) => ({
  ...obj,
  ...listePlayliste[i]
}));
console.log(output);

Answer №3

When working with arrays, the Object.assign() method can be used to merge objects similar to objects.map(). However, it should be noted that Object.assign() will modify the original array. Refer to the code snippet below:

objects = [ { countMedias: 2 },
  { countMedias: 1 },
  { countMedias: 3 },
  { countMedias: 1 },
  { countMedias: 2 } ];
listePlayliste = [ { nom_playlist: 'bbbb' },
  { nom_playlist: 'ccc' },
  { nom_playlist: 'aaaa' },
  { nom_playlist: 'xxxx' },
  { nom_playlist: 'resttttttttt' } ];


for (let i=0; i<objects.length; i++) {
  Object.assign(objects[i], listePlayliste[i]);
}

console.log(objects);

If you want to avoid modifying the original array, consider using Spread syntax instead. See the code snippet below for an alternative approach:

objects = [ { countMedias: 2 },
  { countMedias: 1 },
  { countMedias: 3 },
  { countMedias: 1 },
  { countMedias: 2 } ];
listePlayliste = [ { nom_playlist: 'bbbb' },
  { nom_playlist: 'ccc' },
  { nom_playlist: 'aaaa' },
  { nom_playlist: 'xxxx' },
  { nom_playlist: 'resttttttttt' } ];

var result = [];
for (let i=0; i<objects.length; i++) {
  result.push({ ...objects[i], ...listePlayliste[i] })
}

console.log(result);
console.log(objects);

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

Utilize parent function employing component

Is it possible to add a click listener to a component that triggers a method in the parent template using Vue? <template> <custom-element @click="someMethod"></custom-element> </template> <script> export default { ...

Convert the PHP variable into a JSON object

i am currently working on a project with Codeigniter below is my PHP switch-case section case 'check': $balance = $this->Model_transactions->getUserBalance($this->input->post('userId')); $needToPay = floatval($this->inp ...

Adding Node Modules during the setup of an ElectronJS application

Hey there! I'm currently working on an ElectronJS application designed for developers. One of the key features is checking for the presence of NodeJS on the user's computer. If it's not detected, the app will automatically download and insta ...

I possess an array with a specific structure that I wish to substitute the keys as demonstrated below

The data array is currently structured in this way. I have attempted various methods but have not been able to find a suitable solution. I need to send the JSON below via an AJAX request, however, I do not want the keys 0 and 1 in both child arrays. [sch ...

"Transmitting data via HTTP POST on an Android device

While there have been previous inquiries on this topic, many of the methods mentioned are no longer relevant. I have discovered a new solution: new Thread( new Runnable() { @Override public void run() { try { St ...

Having difficulty locating the index of the column labeled `Clients` within a table; the result being -1

Having some trouble locating the index of the column name Customers within a table using jQuery/javascript. No matter what I try, it always returns -1 let tableDatacy = "Results_Table"; let columnName = "Customer"; let tableHeaders = [] ...

Timing problem with the getJSON function in jQuery

My program seems to be skipping the result of a JSON call. Is there a way I can implement a closure function here or make the program wait for the JSON call to return? function checkIfUsernameIsDuplicate(username) { var functionName = "get_username"; ...

Is it possible to dynamically change the port for an Express server?

Here is a common question that often arises among beginners, as I had the same query when I first started Is there a way to set the port for express without manually coding it or selecting a port yourself? This was something that puzzled me during my init ...

Is there a way to trigger an interact.js event that will reset all draggables back to their original position at coordinates (0, 0)?

I am trying to figure out how to trigger an onmove or drag move event to reset the position of a draggable div to x:0 y: 0. Despite looking at various sources like help topics here and on interact.js main page, I haven't found the right solution yet. ...

Instructions for including packages in .vue files

Within the script section of my .vue file, I have the following code: <script> import get from 'lodash.get'; ... </script> Despite trying to import lodash.get, I keep encountering an error message stating ReferenceError: ge ...

Transferring data from local storage to a PHP server using AJAX

My attempt to transfer data from local storage to PHP using AJAX resulted in an error mentioning 'undefined index data'. chart.php <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script type="t ...

increasing the size of the input thumb compared to the others

Hello fellow React developers, I'm currently learning by coding and I have a question about a slider. I'm trying to make the thumb of the slider bigger, but when I increase its size it doesn't fully display within the input area (as you can ...

Azure webhosting blocks the use of AJAX calls

There is a PHP script hosted on my Azure server that returns JSON when accessed through the browser. However, I am having trouble making an AJAX call to this script as none of my requests seem to go through. The issue remains unclear. You can see a failed ...

Retrieve JSON data and use a button to sort and display markers on a Google Map

Is it possible to modify my function in order to use different PHP files with separate buttons without duplicating the code? Currently, I have a function that displays markers on an external HTML page when a button is clicked. The data is retrieved from fi ...

`vuetify sidebar with a nested menu``

I am trying to enhance the vuetify sidebar menu I created by adding a submenu to a specific title. Despite editing the code and data as shown below, I am unable to see any changes reflected. Below is the code snippet: <v-list flat class="mt- ...

Connect to Node-Red websocket server

My server is running node-red with embedded functionality. I am attempting to set up a new websocket listener on the server, but when I run the code provided, the websockets in my node-red application stop functioning properly. const WebSocket = require(& ...

Identifying the user's location within the application and dynamically loading various Angular scripts

Currently, I am working on a large-scale web application using Laravel and Angular. In this project, I have integrated various angular modules that come with their own controllers, directives, and views. One challenge I am facing is the need to load diffe ...

Having trouble authenticating the CSRF token! Using RAILS API and sending a POST request

I'm having trouble posting a json file with Rails API. I've tried to troubleshoot it, but I can't get it to work. Here is the issue I am facing: Server log: Started POST "/students/" for 127.0.0.1 at 2016-09-17 17:45:33 +0700 ActiveRecor ...

Passing events between sibling components in Angular 2Incorporating event emission in

Having some trouble emitting an event from one component to another sibling component. I've attempted using @Output, but it seems to only emit the event to the parent component. Any suggestions? ...

Adjust an OnDemandGrid utilizing dstore/Rest output through a POST request instead of a PUT request

I am facing a perplexing issue. I have an OnDemandGrid that is editable, and below it, I have a dstore/Rest collection connected to my backend (using PHP). While I can edit the data in the OnDemandGrid, I am unable to save it properly. When it reaches the ...