Combining arrays in Javascript without using the concat method

I am facing a challenge with merging two arrays. Most solutions I have come across suggest using the concat method. However, my requirement is to add a key/value pair from array1 to each object in array2.

The first array (array1) that needs to be merged:

[
    "Basket Abandonment",
    "Downloads",
    "App Version"    
]

This is the second array (array2):

[
    {
        bottom: {
            comp : "",
            details, : "3.1.39 22nd Jul 2015",
            status : "",
            title : "Previous Version",
            value : "8.7%"
        },
        top: {
            details: "3.1.40 25th August 2015", 
            status: "", 
            comp: "", 
            title: "Latest Version", 
            value: "86%",
        }
    },
    {
        bottom: {
            value: "469", 
            title: "Total Reviews", 
            status: "neutral", 
            comp: "same", 
            details: "2 New This Week"
        },
        top:  {
            details: "Version 3.1.40", 
            status: "neutral", 
            comp: "same", 
            title: "Average Rating", 
            value: "4.0"
        }
    },  
    {
        bottom: {
            value: "469", 
            title: "Total Reviews", 
            status: "neutral", 
            comp: "same", 
            details: "2 New This Week"
        },
        top:  {
            details: "Version 3.1.40", 
            status: "neutral", 
            comp: "same", 
            title: "Average Rating", 
            value: "4.0"
        }
    }       
]

In the final combined array, we want to introduce a new key named title for each object by assigning values from the first array. The resulting array should appear as follows:

[
    {
        title: "Basket Abandonment",
        bottom: {
            comp : "",
            details, : "3.1.39 22nd Jul 2015",
            status : "",
            title : "Previous Version",
            value : "8.7%"
        },
        top: {
            details: "3.1.40 25th August 2015", 
            status: "", 
            comp: "", 
            title: "Latest Version", 
            value: "86%",
        }
    },
    {
        title: "Downloads",
        bottom: {
            value: "469", 
            title: "Total Reviews", 
            status: "neutral", 
            comp: "same", 
            details: "2 New This Week"
        },
        top:  {
            details: "Version 3.1.40", 
            status: "neutral", 
            comp: "same", 
            title: "Average Rating", 
            value: "4.0"
        }
    },  
    {
        title: "App Version",
        bottom: {
            value: "469", 
            title: "Total Reviews", 
            status: "neutral", 
            comp: "same", 
            details: "2 New This Week"
        },
        top:  {
            details: "Version 3.1.40", 
            status: "neutral", 
            comp: "same", 
            title: "Average Rating", 
            value: "4.0"
        }
    }       
]

Answer №1

To populate the new title property in the second array with values from the first one, you can use a simple for-loop. However, if you prefer to create a new array without altering the original sources, one approach is to generate a new array by mapping a cloned version of the objects in the second array and assigning the corresponding titles from the first array. Here's an example implementation:

const mixed = objects.map((obj, index) => (clone = {...obj}, clone.title = titles[index], clone));

Below is a demonstration using a custom function applied to your specific arrays:

const titles = [
  "Basket Abandonment",
  "Downloads",
  "App Version"
];

const objects = [
  {
    bottom: {
      comp: "",
      details : "3.1.39 22nd Jul 2015",
      status: "",
      title: "Previous Version",
      value: "8.7%"
    },
    top: {
      details: "3.1.40 25th August 2015",
      status: "",
      comp: "",
      title: "Latest Version",
      value: "86%",
    }
  },
  {
    bottom: {
      value: "469",
      title: "Total Reviews",
      status: "neutral",
      comp: "same",
      details: "2 New This Week"
    },
    top: {
      details: "Version 3.1.40",
      status: "neutral",
      comp: "same",
      title: "Average Rating",
      value: "4.0"
    }
  },
  {
    bottom: {
      value: "469",
      title: "Total Reviews",
      status: "neutral",
      comp: "same",
      details: "2 New This Week"
    },
    top: {
      details: "Version 3.1.40",
      status: "neutral",
      comp: "same",
      title: "Average Rating",
      value: "4.0"
    }
  }
];

const mix = (o, t) => o.map((m, i) => (c = {...m}, c.title = t[i], c));

const mixed = mix(objects, titles);

console.log(mixed);

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

Stop specific characters from being input into a text field

My goal is to restrict the characters allowed in a text box to the following: A to Z in both upper and lower case, Ñ and ñ, and space. I have a function that runs onkeyup: FieldOnKeyUp(el) { !(/^[A-zÑñ-\s]*$/i).test(el.value)?el.value = el.value ...

Creating a File and Resource Manager for Your Express Application: Step-by-Step Guide

I'm interested in creating a website section where users can upload files, such as game mods, for others to download. I envision this section being able to handle a large volume of files and users. How can I achieve this scalability and what architect ...

Is there a benefit to using middlewares instead of the standard built-in functions in Express.js?

Express.js offers a wide range of middlewares that replace built-in functions. One example is body-parser, which parses HTTP request bodies, replacing the built-in function express.bodyParser. body-parser replaces the built-in function express.bodyParse ...

Utilizing GSAP for crafting a dynamic horizontal scrolling section

I am currently working on creating a unique section that transforms into a horizontal scroller once the items (in this case, images) are visible, and then reverts to a vertical scroller once all the items have been scrolled through. My inspiration and ada ...

Stuck at loading: Electron encountering issues with Aurelia Navigation Setup

UPDATE 1: An unexpected challenge has arisen As I endeavored to install and configure Aurelia Navigation with Typescript and Electron by following these instructions: https://github.com/aurelia/skeleton-navigation/tree/master/skeleton-typescript I succe ...

Tips for Maintaining the Execution of a JavaScript Function Within a Class until the Browser Window is Closed (Web Development)

The title might be a little confusing, so let me clarify here: I have implemented a popup that appears in the bottom right corner of a specific page on my website. The popup is working as intended (it shows up when the page is initially opened and can be ...

Parsing through a deeply nested JSON array with PHP

Here is my JSON array: [ { "custClass": [ { "code": "50824109d3b1947c9d9390ac5caae0ef", "desc": "e1f96b98047adbc39f8baf8f4aa36f41" }, { "code": "dab6cc0ed3688f96333d91fd979c5f74", ...

I am unable to illuminate with a mouse event

I'm encountering an issue where I can't add light using the keydown event in a three.js scene. Here's the function that I am using: function putLight(){ light = new THREE.SpotLight( 0xffffff ); light.position.set( 10, 80, 20 ); ...

Chrome runs requestAnimFrame at a smooth 60 frames per second, while Firefox struggles to keep up at

I recently developed a canvas animation using requestAnimFrame and saw great results in Chrome. However, when I viewed it in Firefox, it seemed like a slideshow was running instead of a smooth animation. I'm unsure what could be causing this issue. F ...

Mismatch in the result of the conversion of the string with strtol

After reading through this question, I was unable to find the solution I needed. Therefore, I attempted to utilize strtol in the following way: in = (unsigned char *)malloc(16); for(size_t i = 0; i < (size_t)strlen(argv[2]) / 2; i+=2 ) { long tmp ...

Should Q.all be nested inside another Q.all?

Here's a snippet of my code: let tasks = []; tasks.push(MyModel.update({ _id: 50 }, { Test: 5000 }).exec()); return Q.all([ myPromise, Q.all(dbTasks) ]); I'm wondering if it is appropriate to nest Q.all inside another Q.all. Will the prom ...

Preloading images before loading a div using JavaScript

Can you walk me through implementing object first and then mergeObject in JavaScript? I have an interesting scenario where I need to display the original list followed by a merged list after a short delay. How can I achieve this using JavaScript? Specific ...

Is it possible to create a bot that's capable of "hosting events" using Discord.js?

I am searching for a solution to host "events" using Discord.js. After some research, I stumbled upon this. Although it seems to be exactly what I am looking for, the website does not provide any code examples to help me try and replicate its functionali ...

Top method for enhancing outside libraries in AngularJs

Currently, I am utilizing the angular bootstrap ui third party library as a dependency in my angular application. One question that is on my mind is what would be the most effective method to enhance the functionality of directives and controllers within t ...

Exploring NextJS with Typescript

Struggling to incorporate Typescript with NextJS has been a challenge, especially when it comes to destructured parameters in getInitialProps and defining the type of page functions. Take for example my _app.tsx: import { ThemeProvider } from 'styled ...

confronting #tackling challenges while launching a next.js web application

While trying to deploy my next.js app, I encountered the following issue with #fillNegs in the tailwind node_modules folder. My setup includes node.js version 12.22.0, next.js version 11, and Tailwind version 2.0.2. module.image.null_resource.push (local ...

Ways to retrieve data object within an HTMLElement without relying on jQuery

Within my web application, I have successfully linked a jQuery keyboard to a textbox. Now, I am seeking a way to explicitly call the keyboard.close() function on the keyboard as I am removing all eventListeners from the text field early on. To achieve thi ...

Having trouble loading React bootstrap web when integrating it with a navigation component for routing

Hey everyone! I'm currently working on building a web app using react-bootstrap and implementing BrowserRouter to link all the components together. I've wrapped the index JS with BrowserRouter and added the Switch and Route tags to the navigation ...

Switch out the play pause button on an embedded YouTube video player

Is it possible to customize the play/pause button on YouTube iframes using CSS? I have several iframes and would like to change the default red play button. I've attempted the following code: .ytp-large-play-button{ background: url(play.png); } ...

Angular8 Chart.js customizes the Y axis tick labels

Is there a way to dynamically adjust the Y-axis ticks in a chart.js graph? I attempted to modify them using the following commands: this.chartOptions.scales.yAxes[0].ticks.min = 10; this.chartOptions.scales.yAxes[0].ticks.max = 18; ...