Ways to increase the size of an element within an array using JavaScript

I am currently working on expanding an array in JavaScript. Here is the object below

const items = [
    {
        id: 1,
        name: 'Alice',
        designs: [
            {
                designId: 1,
                designName: "designA"
            },
            {
                designId: 2,
                designName: "designB"
            }
        ]
    },
    {
        id: 2,
        name: 'Bob',
        designs: [
            {
                designId: 3,
                designName: "designC"
            },
            {
                designId: 4,
                designName: "designD"
            }
        ]
    },
{
        id: 3,
        name: 'Carol',
        designs: []
    },
];
[
  { id: 1, name: 'Alice', designId: 1, designName: 'designA' },
  { id: 1, name: 'Alice', designId: 2, designName: 'designB' },
  { id: 2, name: 'Bob', designId: 3, designName: 'designC' },
  { id: 2, name: 'Bob', designId: 4, designName: 'designD' },
  { id: 3, name: 'Carol', designId: null, designName: null },
]

Although it can be done using nested loops, I aim to accomplish this with higher-order functions.

Below is my code snippet

for (let i = 0; i < items.length; i++) {
    for (let j = 0; j < items[i].designs.length; j++) {
        const id = items[i].id
        const name = items[i].name
        result.push({
            id,
            name,
            designId: items[i].designs[j].designId,
            designName: items[i].designs[j].designName
        })
    }
}

Additionally, any insights on performance differences between nested loops and higher-order functions would be greatly appreciated.

Answer №1

If you want to efficiently merge properties from nested arrays in JavaScript, you can utilize the .flatMap() method along with an inner .map() function. By iterating through the array of objects and merging their properties, you can create a single flattened array containing all the merged values:

const tests = [ { id: 1, name: 'taro', designs: [ { designId: 1, designName: "design1" }, { designId: 2, designName: "design2" } ] }, { id: 2, name: 'John', designs: [ { designId: 3, designName: "design3" }, { designId: 4, designName: "design4" } ] }, ];

const res = tests.flatMap(({designs, ...rest}) => designs.map(design => ({
  ...rest,
  ...design
})));
console.log(res);

Edit: If you want to handle cases where the designs array is empty by including default null values for the design objects, you can modify the code to explicitly add those keys when the designs array is empty:

const tests = [ { id: 1, name: 'taro', designs: [] }, { id: 2, name: 'John', designs: [] }, ];

const res = tests.flatMap(({designs, ...rest}) => 
  designs.length 
    ? designs.map(design => ({
       ...rest,
       ...design
      }))
    : {...rest, designId: null, designName: null}
);
console.log(res);

Answer №2

To create the array, you can utilize a combination of Array.reduce and Array.map functions:

const results = tests.reduce((acc, { designs, ...rest }) => [
  ...acc,
  ...designs.map(e => ({ ...rest, ...e }))
], []);

const tests = [
    {
        id: 1,
        name: 'taro',
        designs: [
            {
                designId: 1,
                designName: "design1"
            },
            {
                designId: 2,
                designName: "design2"
            }
        ]
    },
    {
        id: 2,
        name: 'John',
        designs: [
            {
                designId: 3,
                designName: "design3"
            },
            {
                designId: 4,
                designName: "design4"
            }
        ]
    },
];

const results = tests.reduce((acc, { designs, ...rest }) => [
  ...acc,
  ...designs.map(e => ({ ...rest, ...e }))
], []);

console.log(results);

Answer №3

If you utilize the powerful higher-order function Array.prototype.reduce() along with Array.prototype.map()

const updatedArr = tests.reduce((prev, {templates, ...current}) => [
   ...prev, ...templates.map(template => ({...template,...current}));
]      
, []);

The efficiency in your method and this enhanced approach remains consistent because Array.prototype.reduce traverses the entire array while simplifying the process with the initialValue concept.

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

Invoke the function when the user inputs text into the textbox

<textarea name="" id="" #text cols="30" (keydown)="WordCounter()" (change)="WordCounter()" rows="8" [(ngModel)]="user_text" placeholder="Type something here"></textare ...

Customizing CSS in apostrophe-cms Pro using TheAposPallete.vue

Just starting with apostrophe-pro and I've noticed a file named TheAposPallete.vue in the node_modules directory, located at \node_modules@apostrophecms-pro\palette\ui\apos\components This file contains the following CSS: ...

Combining two request.get functions into a single one

Is there a way to combine these two functions into one? I have two APIs: /page1 and /page2. My goal is to merge the two arrays into one because the GitHub API only displays 100 objects per page. request.get({ url: 'https://api.github.com/users/an ...

What is the process of creating multiple entities in Three.js?

I am struggling to create a scenario where multiple objects fall from the top in my project. My attempt at duplicating the code has not been successful. Below is the code snippet I have been working on: var renderer = new THREE.WebGLRenderer({canvas: doc ...

Is there a way to incorporate a unique code onto my webpage, such as the famous Konami code?

I'm on the lookout for a unique twist on the typical Konami code questions. Instead of triggering an alert or redirecting to a different page, I want to hide a specific paragraph on my main page (index.html) by default. When the user enters the Konami ...

Refresh the array of buttons within a JPanel

When I send an array of integers to the constructor panel for the first time, it successfully creates the GUI. However, when I try to update the panel/JFrame with a new array, nothing happens. class panel extends JPanel{ public panel(int matriz[][] ...

Tips for removing cookies with Javascript after an allotted period of time

I need to remove a specific cookie value that I set after a certain time period. For example, I want the cookie to be deleted after 10 seconds. function fullday() { document.getElementById("res").innerHTML="1 day"; document.cookie="day="+1; do ...

Filtering function that works without specific knowledge of keys

I'm working on a JavaScript method to filter a list dynamically without knowing the specific key (s). I've made some progress, but I'm stuck and not sure how to proceed. The foreach loop I have isn't correct, but I used it for clarity. ...

Variations of a particular software package are necessary

My current project requires Expo, React, and React-Native as dependencies. The configuration in the package.jason file looks like this: "main": "node_modules/expo/AppEntry.js", "private": true, "dependencies": { "expo": "^28.0.0", "expo-three": "^ ...

Adding an iframe with inline script to my Next.js website: A step-by-step guide

For my Next.js project, I have this iframe that needs to be integrated: <iframe class="plot" aria-label="Map" id="datawrapper-chart-${id}" src="https://datawrapper.dwcdn.net/${id}/1/" style="width: ...

How can I write an if-else statement in JavaScript with Mongoose for MongoDB?

I am facing a challenge where I need to execute a statement only if the object is not null. If the object is null, I should skip executing anything. Is there a correct way to achieve this? I attempted it on MongoDB Playground but unfortunately, it did not ...

Selling beyond webpack's confines

Today I had an interesting thought and couldn't find much information on it, so I decided to share some strange cases and how I personally resolved them (if you have a better solution, please feel free to comment, but in the meantime, this might be he ...

Preserving the condition of a webpage using socket.io

Currently in the process of developing a card game using node.js as the server, along with web sockets (socket.io) for data transfer between server and client. My goal is to ensure that when a player refreshes the page after cards have been dealt, they wi ...

combining arrays in Node.js

This code snippet defines a function that retrieves an array containing shop details and images for each shop. function listShops(callback) { var array = [3, 4]; async.each(array, function(dat, callback){ async.parallel([ ...

Buttons and links with intricate geometries

I am currently developing a web application using Java/JSF and I am interested in finding out about technologies that would allow me to define intricate shapes as clickable buttons or links. Right now, my only option is to split an image into smaller trans ...

Enhancing the Canvas with JavaScript: Implementing 2048

In my high school computer science class, my partner and I chose to create a unique version of the game 2048 for our final project. Instead of traditional moving tiles, we are implementing a grid with properties like number and color assigned to each til ...

Retrieving ng-repeat object in Angular

How can I retrieve the current object from an ng-repeat on ng-click without using $index? The $index method is giving me the wrong index due to my use of orderBy. Ideally, I would like to be able to click on the object (thumbnail) and have $scope.activePer ...

Updating the Ajax Url dynamically while scrolling

I am trying to update the Ajax URL dynamically, and here is my progress so far: var size=1; var from = 1; window.addEventListener('mousewheel', function(e){ if(e.wheelDelta<0 && from<5){ from++; } else if(e.whe ...

ESLint detects the error "screen not found in @testing-library/vue"

When trying to utilize @testing-library/vue with the screen method imported, I encountered an error from ESLint stating: "screen not found in @testing-library/vue". // The render function doesn't give an error but screen does import { render ...

When utilizing exit-hook with process.on('SIGTERM'), child_process spawn requires two control-c commands to exit properly

I have the following program running: const { spawn } = require("child_process"); const exitHook = require("exit-hook"); exitHook(() => { console.log("Leaving"); }); spawn("my-program", ["my-args"], { stdio: "inherit" }); // Long running server ...