Transforming a collection of Javascript objects into a pure Javascript array

After JSON.stringify-ing my JavaScript object, the output looks like this:

[
    {
        "item_id": null,
        "parent_id": "none",
        "depth": 0,
        "left": "1",
        "right": 4
    },
    {
        "item_id": "1",
        "parent_id": null,
        "depth": 1,
        "left": 2,
        "right": 3
    }
]

I am trying to convert this into a multi-dimensional array that resembles the following structure:

item[0][0] = item_id
item[0][1] = parent_id
item[0][2] = depth
item[0][3] = left
item[0][4] = right

item[1][0] = item_id
item[1][1] = parent_id
item[1][2] = depth
item[1][3] = left
item[1][4] = right

Any assistance on achieving this transformation would be greatly appreciated :)

Edit: With the support of everyone, I have successfully implemented the conversion. Thank you all for your contributions.

Answer №1

To begin, let's consider the original array before using the stringify function. We can iterate through each item in this array and create a new array for each property. Here is an example implementation:

var myObject = X; // representing the original object
var newArray = [];

for (var i = 0; i < myObject.length; i++) {
   var item = myObject[i];
   var subArray = [];
   subArray.push(item["item_id"]);
   subArray.push(item["parent_id"]);
   subArray.push(item["depth"]);
   subArray.push(item["left"]);
   subArray.push(item["right"]);
   newArray.push(subArray);
}

You can find a working example here - make sure to check the console for the result.

Note: I have chosen not to use a for in loop due to concerns about order reliability. While some may trust it, I prefer to err on the side of caution. You can explore other opinions on this topic here.


If you are looking to optimize performance, you could directly create an array from the property values like this:

for (var i = 0; i < myObject.length; i++) {
    var item = myObject[i];
    var subArray = [item["item_id"], item["parent_id"], item["depth"], item["left"], item["right"]];
    newArray.push(subArray);
}

This approach offers approximately double the speed in terms of performance. You can see the comparison here.

Answer №2

What you may have thought was an "object" is in fact a collection of Arrays.

var items = [];
for (var x=0; x<arrayCollection.length; x++) {
   var subArray = [];
   var element = arrayCollection[x];
   for (var y in element) {
      subArray.push(y);
   }
   items.push(subArray);
}

Answer №3

Iterate through the properties of each object in your array and map them accordingly

var mappedItems = yourArray.map(function (object) { 
  var result = [];
    for (var prop in object) { 
      result.push(object[prop]);
    }
    return result; 
});

Answer №4

Utilizing recursion for handling multi-dimensional data objects:

code snippet

 function isArray($obj) {
    return Object.prototype.toString.call($obj) === '[object Array]';
}

function processObject(data) {


    if(isArray(data)){
        return (processArray(data));
    }

    var result = [];
    for (var i in data) {
        var item = data[i];
        if (item === null) { // considering null as an object type..!
            result.push(item);
        } else if (isArray(item)) {
            result.push(processArray(item));
        } else if (typeof item === 'object') {
            result.push(processObject(item));
        } else {
            result.push(item);
        }
    }
    return result;
}

function processArray(data) {
    var result = [];

    for (var i = 0; i < data.length; i++) {
        var item = data[i]; 
        if (item === null) { // considering null as an object type..!
            result.push(item);
        } else if (isArray(item)) {
            result.push(processArray(item));
        } else if (typeof item === 'object') {
            result.push(processObject(item));
        } else {
            result.push(item);
        }
    }
    return result;
}

var processedData = processObject(data);
console.log(processedData);

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 is the technique for invoking methods of the Joi class without the need to instantiate an object?

I recently delved into using the Joi NPM module and found it confusing that although it is described as a class in the documentation, it does not require creating a class object like var joi = new Joi();. Can you explain how this works? My understanding o ...

Aggregating information from JSON to populate a list

I came across a JSON data with the following structure: { "items": [ { "kodeHp": "C-1", "firstName": "iman", "lastName": "firmansyah", "email": &q ...

Storing values in an array when checkboxes are selected within an ng-repeat loop in AngularJS

I am facing a situation where I need to populate an array with values when a checkbox is checked within an ng-repeat iteration. <li ng-repeat="player in team.players"> <div class="row"> <div class="col-md-3 m-t-xs"> <inp ...

Tips for Integrating a Facebook Shop Page into Your Website

Can a Facebook shop page be integrated into a website? Any guidance on how to accomplish this task would be greatly valued. ...

Are there any techniques for running unit tests on a Vue.js transition?

I have been working on a Vue component that includes a transition with a dynamically generated name. My challenge is to test whether the transition name is correctly set based on the props I pass into the component. Below is the code snippet of the compone ...

Utilizing iOS Local Storage for Efficient Form Submission Handling

I feel like my brain is on the verge of exploding. I just can't seem to get this to work as intended, and I'm struggling to pinpoint the issue. Currently, I have a form that needs to be processed using AJAX. Before proceeding with that, I want ...

What is the best way to attach an event listener to detect the coordinates where a click occurs inside a div element?

Imagine a situation where you have a div container measuring 200px by 500px. The goal is to implement an event listener that can identify the x and y coordinates within this div when it is clicked. What would be the approach to achieve this in React? ...

Moving data from one table to another and making changes or removing it

After successfully adding data from one table to another using .click, I encountered an issue. Whenever I utilize the search field in the top table, it clears the appended rows in the bottom table. I am looking for a solution to have these tables generate ...

Encountering SCRIPT1014 and SCRIPT1002 errors within an Angular4 application when using Internet Explorer 11

My Angular 4 application runs perfectly in various browsers. However, when trying to launch it in Internet Explorer version 11, I encounter the following two errors: SCRIPT1014: Invalid character addScript.js (9,1) SCRIPT1002: Syntax error main.bundle.js ...

When trying to set up Plaiceholder in a Next.js/Webpack 5 environment, you may encounter the following issue: "Error: Module not found - Can't resolve 'child_process

While working on my Next.js application, I encountered an issue after installing/importing Plaiceholder for generating placeholder images. The error message I received is: Module not found: Can't resolve 'child_process' Node version: 14.18. ...

Attempting to employ jQuery to generate a text input that allows for inputting multiple incorrect answers

I am putting together a webpage for a friend who has allergies. The idea is that users can input a food item, and the page will indicate whether or not my friend is allergic to it. I have compiled an array of his food allergies, and the goal is for the pag ...

JavaScript has been used to modify a cell's URL in jqGrid

Currently, I am utilizing struts2-jqgrid along with JavaScript. After the jqgrid has finished loading, it retrieves <s:url var="updateurl" action="pagosActualizar"/>. Subsequently, in the HTML view source, jqgrid generates options_gridtable.cellurl = ...

Retrieving data from an anonymous function in AngularJS and outputting it as JSON or another value

Within the following code, I am utilizing a server method called "getUserNames()" that returns a JSON and then assigning it to the main.teamMembers variable. There is also a viewAll button included in a report that I am constructing, which triggers the met ...

There was a json parsing error that occurred due to an uncaught TypeError. The error message stated that the 'in' operator cannot be used to search for '1009'

I'm currently working on a project where my application makes an Ajax call to a PHP script that returns data encoded in json_encode. The PHP script is returning the data as expected. However, when attempting to parse it in jQuery, I encounter a conso ...

Display and conceal div with Jquery as you scroll to specific points on a mobile device

I'm looking to create a dynamic div that appears and disappears based on the user's scroll position. Here is what I have so far: $(document).scroll(function() { var y = $(this).scrollTop(); if (y > 200) { $('.float-contai ...

Sending specific names as properties

Looking to streamline my repetitive form inputs by abstracting them into a component, I want the following functionality: <InputElement title="someTitle" v-model="someName" @blur="someFunction" name="someName" type="someType"> The desired output wo ...

The next image is crashing on every device except for mine

On my device, the next image works perfectly, but it crashes on every other device. Here is the JSX code: <div className="img-container-homePage"> <Image src="/catI.jpg" alt="Cat" layout="fill" /> < ...

I'm getting an error about uncaught products in a collection - can you help me understand what this means and how to

My next.js website, which fetches products from Shopify, was working flawlessly until a few months ago when it suddenly stopped building on the development server. Now, whenever I try to run the website locally, I am encountering a "Cannot read properties ...

Animating a Canvas to Follow Mouse Coordinates

I am looking for a way to animate a circle moving towards specific coordinates, similar to the game . I have attempted using the jquery animate() function, but it is too slow due to the constant updating of the target coordinates. Is there a faster metho ...

The initial setTimeout function functions correctly, however the subsequent ones do not operate as expected

I have developed the following code: bot.on('message', message=> { if(message.content === "come here") { message.channel.send('hey'); setTimeout(() => { message.channel.send('i am here' ...