Is there a way to instantiate a new object within the same for loop without replacing the ones created in previous iterations?

My current issue with this exercise is that as I convert the first nested array into an object, the iteration continues to the next nested array and ends up overwriting the object I just created.

I'm wondering how I can instruct my code to stop iterating over the converted object and instead create a new one for each nested array.

In addition to my previous question, the exercise requires me to store these newly created objects in an array. My plan was to create the objects first and then push them into a placeholder array variable at the end. Is there a more efficient way to do this within the loop?

I would appreciate any assistance, as I am still relatively new here so please be kind!

Here is what I have done so far along with the instructions:

*I am tasked with writing a function called “transformEmployeeData” that converts employee data from one format to another.

The input will look like this:

[
    [
        ['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']
    ],
    [
        ['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']
    ]
]
The expected output should be:</p>

[
    {firstName: 'Joe', lastName: 'Blow', age: 42, role: 'clerk'},
    {firstName: 'Mary', lastName: 'Jenkins', age: 36, role: 'manager'}
]

<p>Please note that the input may vary in rows or keys from the given sample.</p>

<p>If, for example, the HR department adds a “tshirtSize” field to each employee record, your code should be able to handle it flexibly.*</p>

<pre><code>function transformEmployeeData(employeeData) {
    debugger;
    var obj = {};
    for (var i = 0; i < employeeData.length; i++) {
        for (var y = 0; y < employeeData[i].length; y++) {
            obj[employeeData[i][y][0]] = employeeData[i][y][1]
        }
    }
    return obj
}

Answer №1

Utilize the .map() function on the outer array and apply .reduce() on the inner array.

var data = [
    [
        ['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']
    ],
    [
        ['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']
    ]
];

var result = data.map(arr => arr.reduce((acc, [key, value]) => ({[key]: value, ...acc}), {}));

console.log(result);


Another approach:

var data = [
    [
        ['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']
    ],
    [
        ['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']
    ]
];

var result = data.map(arr => Object.assign({}, ...arr.map(([key, value]) => ({[key]: value})));

console.log(result);


You can also switch to using actual Maps instead of objects. Then you could do this:

var data = [
    [
        ['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']
    ],
    [
        ['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']
    ]
];

var result = data.map(arr => new Map(arr));


for (const map of result) {
  for (const [key, value] of map) {
    console.log(key, value);
  }
  console.log("----------");
}

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

What could be causing NgModel to fail with mat-checkbox and radio buttons in Angular?

I am working with an array of booleans representing week days to determine which day is selected: selectedWeekDays: boolean[] = [true,true,true,true,true,true]; In my HTML file: <section> <h4>Choose your days:</h4> <mat-che ...

Manipulating Object origin data

I'm unsure if this can be achieved. I am aiming to create a header and footer that remain the same while only switching the content pages. The resources I have at my disposal cover HTML, JS, CSS, and JQuery. Below is a simplified version of my curre ...

Managing the display of an extensive list of items in react - best practices

I'm facing a challenge with performance as I have a significant number of items to render and the data is constantly being updated in real-time via socket-io. How can I optimize for performance when the table of items is being rendered frequently due ...

Cannot upload pictures using pixi.js PIXI.Texture.from()

I'm currently developing a web game using React with PixiJS. I am trying to incorporate images from my local directory into Pixi.js. For reference, I found this helpful website: Here are the snippets of code that I have used: import * as PIXI from & ...

Struggling to remove an element from a collection of structures in C#? Feeling confused by the conflicting advice out there

After researching this topic, I've come across conflicting answers. Assistance is greatly appreciated! For an assignment, the task at hand involves creating a structure of arrays. The goal is to delete an entry in one instance and modify it in another ...

Ways to enable automatic scrolling of a page as the content expands (Utilizing collapsible elements)

For a recent project I've been working on, I decided to include 4 collapsible text boxes. However, I encountered an issue where opening content1 would expand and push down content2-4, requiring the user to manually scroll to view the remaining collaps ...

JavaScript variable not refreshing its value after submitting an HTML form

In my HTML form, I have 8 textboxes enclosed in div tags with IDs ranging from fa1 to fa8. By default, two of the textboxes are visible while the remaining six are hidden. To toggle the visibility of these divs, I've implemented two buttons - addfa an ...

Transforming an array into a JSON object

I currently have an array structured like this: [ 'quality', 'print-quality: 4', 'x-dimension', 'Value: 21590', 'Value: y-dimension', 'Value: 27940', 'Value: ', 'Valu ...

When using jQuery, the script will execute successfully only when running it chunk by chunk in the console, rather than running the

As I tidy up an html page, my main task is to remove anchor tags and keep the text nodes. To achieve this, I am enclosing all text nodes (without any surrounding elements) within the <asdf> tag. Additionally, I am deleting empty elements such as < ...

Issue with Auth0 not properly redirecting to the designated URL in a React application

auth.js import auth0 from 'auth0-js'; export default class Auth { constructor() { this.auth0 = new auth0.WebAuth({ domain: '<properURL>', clientID: '<properID>', re ...

Adding a line and text as a label to a rectangle in D3: A step-by-step guide

My current bar graph displays values for A, B, and C that fluctuate slightly in the data but follow a consistent trend, all being out of 100. https://i.stack.imgur.com/V8AWQ.png I'm facing issues adding lines with text to the center of each graph. A ...

How to Make a Zigzag Formation in three.js?

I have been working on developing a 3D tool and was in need of a zigzag structure. I managed to create it by iterating a function that produces 'V' multiple times, but now I am looking for a way to achieve the same effect using a single geometry ...

Top method for stacking several divs in a vertical line

In search of the most effective method for organizing numerous dynamically generated divs (all with identical widths) in a vertical stack, two potential solutions have emerged: Utilize float:left... Implement an unordered list and enclose each div within ...

A simple program capable of holding two variables

To create a calculator, I want to implement a process where the user clicks buttons to input numbers into a display box. For instance, clicking 3 and then 2 should display as 32 in the input box. After that, if I click on the "+" button, it should remove t ...

Generate a new tree structure using the identifiers of list items within an unorganized list

Attempting to convert the id's of li's in a nested unordered list into valid JSON. For example, consider the following list. To be clear, the goal is not to create the UL list itself, but rather the JSON from the li id's <ul class="lis ...

The use of event.returnValue in jQuery has been marked as deprecated

Every time I create a webpage using jQuery version , I encounter a warning message in the Console of Google Chrome. Is there a specific piece of code I can use to avoid this warning? Note that I am currently learning jQuery. The warning reads: event.retu ...

What is the best way to activate a modal in the parent component when a button is clicked in the child component?

Currently I have the following setup: panelHeader.vue (which is a child component) index.vue (the parent component where my main list view is) panelHeader.vue <template> <v-row> <div class="panelHeader"> ...

The length of the Array is accurate

Hey there! I'm facing an interesting challenge in my second semester of object oriented programming. For my first project in my intro to java course, I need to create a Date class that calculates the days elapsed from January 1st of the year. I have t ...

Error: Unexpected character encountered

When attempting to parse an array of objects enclosed in double quotes, I encountered an error: Uncaught SyntaxError: Unexpected token ' var test = "[{'key' :'D', 'value': 'Deceased Date'},{'key' ...

The .load() function seems to have a problem with my slider widget

I am facing an issue with a slider on my page that displays posts from a specific category. When the user clicks on "next category", the content slides to the left and new content is loaded along with its respective slider. The problem arises when the loa ...