Manipulating arrays of objects using JavaScript

I am working with an array of objects represented as follows.

data: [ {col: ['amb', 1, 2],} , {col: ['bfg', 3, 4], },]

My goal is to transform this data into an array of arrays like the one shown below.

[ [{a: 'amb',b: [1], c: 'red'}, {a: 'amb',b: [2], c: 'orange'}], 
  [{a: 'bfg',b: [3], c: 'red'}, {a: 'bfg',b: [4], c: 'orange'}] 
]

I have attempted a solution outlined below.

let arrInner: Array<any> = []
let arrOuter: Array<Array<any>> = []

_.forEach(data, (item, i) => {
    //create two objects redObj and orangeObj

    redObj = {
      a: item.col[0].toString(),
      b: [item.col[1] as number],
      c: 'red'
    }
    orangeObj = {
      a: item.col[0].toString(),
      b: [item.col[2] as number],
      c: 'orange'
    }
    
    //put those two objects into an inner array
    arrInner.push(redObj)
    arrInner.push(orangeObj)
    
    //assign the inner array to the outer array
    arrOuter[i] = arrInner
})

However, when I check the values in arrOuter, it does not match my expected output. What could be the issue here and how can I correct it?

Answer №1

Ensure that a new arrInner is created for each iteration of the forEach loop and then add it to arrOuter.

let arrOuter: Array <Array <any>> = []

_.forEach(data, (item, i) => {

  //create redObj and orangeObj objects

  redObj = {
    a: item.col[0].toString(),
    b: [item.col[1] as number],
    c: 'red'
  }
  orangeObj = {
    a: item.col[0].toString(),
    b: [item.col[2] as number],
    c: 'orange'
  }

  //add these two objects to an inner array
  let arrInner = [redObj, orangeObj]

  //push the inner array into another array
  arrOuter.push(arrInner)
})

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

Accessing Route Parameters from Any Component

If my URL follows this structure: /blog/[post_id]/something What's the best practice for passing $post_id to any component within the tree? I'm familiar with retrieving route parameters using getInitialProps, but I struggle with passing values ...

The issue arises in React when input elements fail to render correctly following a change in value, specifically when the keys remain identical

Click here to view the code sandbox showcasing the issue The code sandbox demonstrates two versions - a working one where Math.random() is used as the key, and a not working one where the index of the array is used as the key. When the array this.state.v ...

There was an issue encountered while parsing the JSON data - "SyntaxError: Unexpected token . was caught."

Encountering an error in Chrome while parsing JSON data. The JSON sample can be found at this link. It is valid JSON and the server is sending the correct Content-Type value (application/json). Uncaught SyntaxError: Unexpected token . Firefox shows a sli ...

I am encountering the error message "Utils is not defined" while attempting to generate a chart using chart.js

Attempting to replicate the example provided in chart.js documentation : link to example Unfortunately, I am encountering the error: Uncaught ReferenceError: Utils is not defined Despite its simplicity, I am struggling to identify the issue...! ...

What is the best way to determine which option is most suitable: types, classes, or function types in TypeScript for

Currently, I am developing a small todo command line utility with a straightforward program structure. The main file is responsible for parsing the command line arguments and executing actions such as adding or deleting tasks based on the input provided. E ...

When working with Angular Universal, using d3.select may result in a "reference error: document is not defined" in the server.js file

I'm currently working on an Angular project that uses server-side rendering to generate D3 charts. Each chart is encapsulated within its own component, such as a line-chart component which consists of TypeScript, spec.ts, HTML, and CSS files for rende ...

Performing a task after a process has finished

Currently, I'm working with node JavaScript and facing an issue where I need to run a new function after a loop has completed. In the code snippet provided below, // loop through objects in data, to process it represents a basic for loop iterating ove ...

Using ExpressJS to generate a page with inputs

Using ExpressJS, I have created an Object of the IndexController in my router (index.js) and passed a String as a constructor argument. I then attempted to call the showDefaultFeed method. Expected output from "index.hbs" view was to print the argument pa ...

How to validate text from a <span> tag using Selenium WebDriver and JavaScript

Is there a way to retrieve the value from the span tag using this code snippet? var error = driver.findElement(webdriver.By.id('error-container-text')).getAttribute('innerHTML'); When I run the above code, I get a response that looks ...

Encountering Axios errors while executing API calls at a high frequency

Recently, I have been facing some challenges with making API calls from localhost using axios in a loop. While it works smoothly at times, most often I encounter errors like: cause: Error: connect ECONNREFUSED ::1:8000 at TCPConnectWrap.afterConnect ...

Retrieving multiple checkbox values using JavaScript

When submitting a form using ajax and jquery, I encountered an issue with multiple checkboxes that are not posting values to the database. Here is the relevant HTML/PHP code snippet: while($row = mysql_fetch_assoc( $result )) { echo '<input ...

What is the best way to trigger a JavaScript function to execute as soon as the innerHtml has been modified via Ajax

Utilizing Ajax to dynamically update the content of a div upon clicking a link is my current project. I am seeking guidance on how to call a JavaScript function once the file has been retrieved from the server and the div's content has been replaced. ...

Difficulties arise when trying to pass all data inputted on a form using formData in conjunction with the fetch API

Why is my formData appearing empty when sent to my express+mongodb server? I'm having some issues with querySelector and addEventListener, but for now that's manageable. However, I am struggling to find a way to successfully send all the values o ...

What is the method for installing particular versions or tags of all npm dependencies?

We are embarking on a complex project that involves the use of numerous node modules and operates within a three-tiered development framework. develop stage production Our goal is to distribute modules to our private registry with tags for develop, stag ...

the status of the XMLHttpRequest Object within the realm of jQuery AJAX

When using traditional JavaScript AJAX, we monitor the readystate property to determine the status: 0 - The request is not initialized 1- The request has been set up 2 - The request has been sent 3 - The request is in process 4 - The request is compl ...

Looking to showcase elements within an array inside an object using ng-repeat

In this JSON dataset, we have information about various anchoring products. These products include anchors, cleats, snubbers, shackles, and more. When it comes to displaying these products on an HTML page using Angular, make sure to properly reference the ...

Preserve multiple selected values post form submission using PHP, HTML, and JavaScript

How can I retain the selected values in a form after it is submitted? My current code functions correctly when only one value is selected, but does not maintain all selected values when multiple are chosen simultaneously. Any assistance would be apprecia ...

The smooth scrolling feature fails to function properly in Lenis when clicking on links with specified IDs

Is there a reason why the scroll-behavior: smooth property doesn't function properly when Lenis library for smooth scrolling is included? It seems to work fine when the Lenis code is commented out, but once it's added back in, the scrolling isn&a ...

AngularJS ng-include nested form configuration

My application utilizes nested ng-includes. The outer include is a login screen for one application while the inner ng-include includes two templates. The login screen is designed in two steps where the email is checked first and then the password entered. ...

What could be causing the sporadic functionality of my jQuery image resizing code?

Seeking help for an issue I am facing with my jQuery code. I have been trying to scale a group of images proportionally within an image carousel using jCarousel Lite plugin. However, the resizing code seems to work randomly and I can't figure out why. ...