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

"Bootstrap is functioning properly on my local environment, but it seems to

Utilizing the MVC framework and bootstrap has been successful for optimizing my website locally. However, when I upload it to the server, none of the CSS is being rendered. Additionally, the front page, meant to be a carousel slider, appears as a vertical ...

Ways to automatically style the child divs within a parent div

I'm trying to figure out how to float a parent div with child divs of different widths and heights while maximizing the use of space and not being affected by absolutely positioned elements. For reference, here's an example: http://jsfiddle.net ...

JQuery UI autocomplete vanishes instantly without any warning

I am encountering an issue with JQuery UI's autocomplete feature where the dropdown results do not stay visible. While debugging, I noticed that the list briefly appears before disappearing. Below is my code snippet: HTML: <input type="text" plac ...

Upon initial page load, React JS is unable to fetch the data but it functions correctly when triggered by a click

Here is the code I am working with: var CommonHeader = require('./header/CommonHeader.jsx'); var ListOptions = require('./header/ListOptions.jsx'); var SortableTable = require('../shared/SortableTable.jsx'); var ColumnDefinit ...

The act of exporting an enum from a user-defined TypeScript path leads to the error message "Module not

I have set up a custom path as explained in this particular discussion. "baseUrl": ".", "paths": { "@library/*": [ "./src/myFolder/*" ], } Within this module, I am exporting an Enum. export enum EN ...

Upon exchanging data with the router located in the navigation bar, a continuous loop occurs as I initiate the download operation involving the electron-dl and electron-download-manager tools

When I switch to the router in the navbar, a loop occurs when I try to initiate the download process. I've been struggling with this issue for the past 2 days and can't seem to find a solution. function downloaddosya1() { console.log("Fi ...

A guide on extracting data from various HTML elements effectively with JavaScript

I'm searching for a universal technique to extract values from multiple HTML elements. For instance: <div>Experiment</div> <select><option>Experiment</option></select> <input value="Experiment" /> These thr ...

Using ASP.NET MVC and jQuery Ajax to close and refresh a parent table from a modal dialog

I am relatively new to both MVC and jQuery, and I'm struggling to make them work together. I've managed to put together a modal dialog form with an ajax postback, but the UI is presenting challenges for me. Despite looking for examples of MVC and ...

Explore the XML format within a JavaScript string

Currently, I am retrieving a string from PHP using AJAX. This string contains data from a database formatted in XML tags. Upon receiving this string in JavaScript, my objective is to display it as an XML document on the web browser to verify its proper fo ...

The date picker feature of Jquery Mobile is not appearing on the popup field

I implemented the jtsage jquery mobile date picker, and I am facing an issue where the date picker appears behind the popup instead of in front of it when the text inside the popup is clicked. Here is a snippet of my code: <div data-role="content"> ...

execute a function imported from another file within an express application

To simplify the process of scraping around 20 websites, I have decided to create separate documents for each site in which to contain the scrape function. However, every time I attempt this, I encounter the following error: function scrape(url, callback) ...

A guide on decoding neatly formatted JSON using GSON

Currently, I am interfacing with various APIs that produce JSON responses formatted in a "prettyprinted" manner rather than the standard one-line format. For instance: [ { "Field1.1": "Value1.1", "Field1.2": "value1.2", "Field1.3": "Value1. ...

Handling Errors in Asynchronous Functions with JavaScriptLet's explore the best practices for

I am a beginner in javascript and recently delved into async/await. After going through various resources, I gained a basic understanding. However, while experimenting with some code examples, I encountered unexpected results which left me puzzled about wh ...

Executing JavaScript function by clicking on <img>

I've been developing a website similar to YouTube, and I'm facing difficulties with the Like/Dislike feature for comments. Currently, I have implemented it in the following way: when a user clicks on an image (thumbsUp.png or thumbsDown.png), a ...

Activate the audit command for the npm enterprise registry

I'd like to know how to activate the npm audit command in my npm enterprise registry. Whenever I attempt to run the npm audit command, I encounter the following error: { "error": { "code": "ENOAUDIT", "summary": "Your configured registry ( ...

How can I use PHP to retrieve a specific JSON post by passing it as a parameter in the URL?

I'm facing a challenge with creating a RESTful API using PHP without any frameworks or databases. I've successfully parsed JSON data in PHP, but I'm struggling to access a specific post based on the query parameter entered in the URL. Here ...

Retrieve data from the api

Can someone provide the JavaScript code to loop through an API, extract the coordinates/address, and map it? Here is a simple demonstration of fetching the API data: const fetch = require("node-fetch"); fetch('url').then(function (resp ...

Exploring the Dynamic Duo: Laravel Echo and JQuery

After including Echo in Vue.js' resources/assets/js/bootstrap.js, one of my components is throwing an error The error message states: "Error in mounted hook: 'TypeError: $ is not a function'" When I remove the Echo import, everything run ...

Investigating Jquery Flip Card Issues

Looking to create a set of flip cards using HTML, CSS, and jQuery. Currently facing an issue where only the first card is flipping when clicked. Any suggestions on how to modify the jQuery code to make it work for all cards would be highly appreciated. C ...

What is the best way to handle this JSON format in Android development?

Struggling to Decode the Following JSON Data Structure? { "district": [ { "1": { "name": "Lucknow", "block": [ { "1": "Block1", "2": "Block2", ...