Adding a dynamic key-value pair object to an array using the JS push method

In my programming challenge, I am dealing with an array of objects that have dynamic keys and values. The structure is a bit complicated, but here's a simplified version:

let products_row = [
  {
    id: 1,
    category_id: 11,
    options: {
      'modelName1': {
        size: '2 feet',
        colour: 'red',
        is_new: true
      },
      'modelName2': {
        size: '4 feet',
        colour: 'black',
        is_new: true
      },
    }
  },
  // More objects...
]

The desired result format should look like this:

let resultArray = [
  {
    id: 1,
    category_id: 11,
    model: 'modelName1',
    size: '2 feet',
    colour: 'red',
    is_new: true
  },
  // More results...
]

I've attempted to transform the data but encountered some issues. Here's what I tried:

let productsData = [];

products_row.map((product) => Object.entries(product.options || {}).map((model) => {            
    return productsData.push({
        model: model[0],
        [Object.keys(product).find(key => !['id', 'category_id'].includes(key))]: product[Object.keys(product).find(key => !['id', 'category_id'].includes(key))],
        ...model[1]
    });
}));

console.log(productsData);

However, the output doesn't include all data as intended. It seems like I'm struggling to retain the previous key-value pairs. Here's the incomplete result:

[
  {
    model: 'modelName1',
    id: 1,
    size: '2 feet'
  },
  // Incomplete results...
]

I'm currently stuck at this point and would appreciate any guidance or assistance. Thank you.

Answer №1

Utilizing both flatMap and map
The main purpose of flatMap is to flatten an array returned by map

[
[{...1},{...2}],
[{...3},{...4}]
]

resulting in a flattened array like this:

[
{...1},{...2},
{...3},{...4}
]

let products_row = [{id: 1,category_id: 11,options: {'modelName1': {size: '2 feet',colour: 'red',is_new: true},'modelName2': {size: '4 feet',colour: 'black',is_new: true},}},{id: 2,category_id: 21,options: {'modelName11': {size: '2 feet',colour: 'white',is_new: false},'modelName12': {size: '4 feet',colour: 'white',is_new: false},}},{id: 3,category_id: 31,options: {'modelName21': {size: '8 feet',colour: 'white',is_new: false},'modelName22': {size: '4 feet',colour: 'black',is_new: true},}},{id: 4,category_id: 41,options: {'modelName31': {size: '8 feet',colour: 'red',is_new: true},'modelName32': {size: '8 feet',colour: 'red',is_new: true},}}]

let x = products_row.flatMap(({options,...rest}) => Object.entries(options).map(([k,v]) => ({...v,...rest,model:k}))

console.log(x)

Answer №2

Understanding and improving your solution can be a challenging task, making it difficult for me to rectify the code.

Your goal is essentially to extract options from each object and combine them with the remaining data in the object, meaning you need to iterate through the options for each product row.

There are multiple approaches to accomplish this objective, such as using flatMap as suggested by @cmgchess. Another way to tackle this issue is demonstrated below:

let result = [];

products_row.forEach(({ options, ...rest }) =>
  Object.values(options).forEach((b) => result.push({ ...rest, ...b })),
);

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

"Ensuring Proper Validation for Forms with JavaScript: A Step-by-Step Guide

Here is a sample Javascript form: <form id="loginForm" name="loginForm" action="/create_session/" method="post">{% csrf_token %} <table border="0" cellpadding="0" cellspacing="0" id="id-form"> <tr> <th valign=" ...

I am currently attempting to generate a chart that displays information on countries utilizing the restcountries API. Despite being a beginner in this area, I have encountered some challenges and am seeking guidance

I'm struggling to display detailed information for each country separately. Whenever I try to loop through the data, all the contents end up getting merged into a single cell. What can I do to achieve the desired result? https://i.stack.imgur.com/dZS ...

Utilizing the Vue feature of dynamic route naming within a component's function

Currently, I am working on creating a dynamic view rendering using Vue and Laravel. However, I am facing difficulty in understanding how to pass the dynamic parameter to the component function. Router.map({ '/cms-admin/:page': { comp ...

Click on the image to view in a separate window

I am looking for assistance with a script that can open an image in a new page, not a new window. I have a specific HTML page designated for displaying various images when clicked on. If anyone has any ideas or guidance on how to achieve this, it would be ...

Tabbed form design using Twitter Bootstrap

Currently, I am working on a website using the Bootstrap framework. My goal is to create a single page that features a pop-up form with two or three tabs. Specifically, I envision these tabs as "The Markup," "The CSS," and "The JavaScript." While I have ma ...

What is the best way to send props from a child component to its parent in a React

I'm a beginner in React and I'm attempting to develop a "CV-Generator" similar to the one shown here. In this application, whenever a user inputs data in any of the input fields, it is automatically displayed in the render preview on the right si ...

Check out the Pa11y JSON configuration file specifically designed for actions by visiting the following link: https://github.com/pa11y/pa11

Our automated accessibility testing is conducted using the Jenkins CI tool with the help of pa11y. Below is the Jenkinsfile used to execute these tests: node('mypod') { container('centos') { def NODEJS_HOME env.NODEJS_HOME = "${t ...

How to Retrieve the Key-Value Pairs from an Object Array in C#

Hey everyone, I'm currently working on extracting key and value pairs from an array of objects in my webmethod using AJAX. However, I seem to be facing some issues with this process. Below is a snippet of my AJAX code: var ShedulerTableCount = $(&apo ...

The server appears to be active, but there is a lack of content rendering when using React, Node

When I attempt to run the code in app.jsx, nothing displays even though the index.html is functioning properly. Code from Server.js: var express = require('express'); server.js page var app = express(); app.use(express.static('public' ...

The Wikipedia API is unable to be loaded using the XMLHttpRequest

I have encountered this error before on this platform, and although I managed to fix it, I am seeking a more in-depth explanation of the solution. For a project where I am learning, I decided to create a Wikipedia Viewer application. The first step was to ...

Is there a way to display "not found" if the code's output is blank?

Incorporating an "ajax select" and "while scrolling load data" script has been successful for me. However, I'm struggling with displaying a "not found data" message in div.status when the output variable on animals.php is empty. index.html <!DOCT ...

Loop with an array of structures

Currently delving into the world of C and exploring structures, I've encountered some unexpected behavior that I can't quite wrap my head around. I'm eager to understand why this is happening. Here's the code snippet causing me confusi ...

Tips for implementing a wait time for individual items in bee-queue

I've encountered an issue with the delayUntil function in the bee-queue library when creating a queue. await queue .createJob(process) .timeout(60 * 1000 * 2) .retries(2) .backoff('fixed', 60 * 1000) ...

Is it possible to modify a JavaScript array variable without having to refresh the page by utilizing Ajax?

Is it possible to update a JavaScript array variable without having to reload or refresh the page? I have an existing list of data in an array, and I retrieve additional data using PHP and Ajax. Now I want to add the new data obtained from PHP Ajax to th ...

Using HTML and JavaScript to implement a dragging functionality on a canvas element

After creating a square grid using HTML canvas, I've added a drag feature that allows users to draw rectangles by dragging over the grid. However, it seems that non-rectangle shapes can also be drawn in certain cases. Let's delve into an additio ...

What causes the scrollbar to move while I am dragging the div downward on the page?

$('#aaa').draggable(); * { margin: 0; padding: 0; } #aaa { width: 800px; height: 800px; position: absolute; background: red; } .wrap { height: 2000px; position: relative; ; } <div class="wrap"> < ...

personalized XMLHttpRequest method open

var open = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function(method, uri, async, user, pass) { this.addEventListener("readystatechange", function(event) { if(this.readyState == 4){ var self = this; var respons ...

Encountering issues accessing the key value 'templateUrl' in Angular6

I have an object in my component.ts file that I need to iterate through in the HTML template using a ui-comp-menu element. menuObject = [{ 'labels': 'Content1', 'templateUrl': 'assets/partials/sample.html ...

The script is not functioning properly when placed outside of the HTML body tag

I have a main template that is functioning properly with the layout I've included here. However, I am facing an issue when trying to organize the scripts within one block. Specifically, when I move one of the scripts from the body section to the head ...

CSS guidelines for layering shapes and divs

Currently, I am in the process of developing a screenshot application to enhance my understanding of HTML, CSS, and Electron. One of the key features I have implemented is a toggleable overlay consisting of a 0.25 opacity transparent box that covers the en ...