Error converting object to array

I recently created a function to transform an object into an array.

Function:

function convertObjectToArray(obj) {
    const result = [];
    
    for (const [key, value] of Object.entries(obj)) {
        if (typeof value === 'object' && value !== null) {
            result[key] = convertObjectToArray(value);
        } else {
            result[key] = value;
        }
    }
    return result;
}

The object I am attempting to convert:

const obj = {
    "1129931367": {
        "id": 10,
        "amount": 1,
        "assets": {
            "appid": 252490,
            "app_name": "name",
            "classid": 1129931367,
            "icon_url": "url",
            "tradable": 1,
            "name": "name",
            "market_name": "market name",
            "market_hash_name": "market hash name",
            "sell_listings": 3215,
            "sell_price": "0.10",
            "updated_at": "17-Dec-2022"
        },
        "market_tradable_restriction": 7,
        "market_marketable_restriction": 7,
        "tags": [
            {
                "category": "category",
                "internal_name": "internal name",
                "localized_category_name": "localized category name",
                "localized_tag_name": "localized tag name"
            },
            {
                "category": "category",
                "internal_name": "internal name",
                "localized_category_name": "localized category name",
                "localized_tag_name": "localized tag name"
            }
        ]
    }
}

Output:

(1129931368) [empty × 1129931367, Array(0)]

However, when I attempt to convert the desired object, it generates numerous empty arrays and I am unsure of the reason behind this. Could the issue lie within the Object or my function itself?

Thank you for any assistance provided!

I have made several attempts at revising the function, but this version is the closest I have come to achieving my goal.

Answer №1

The reason for this issue is the absence of utilizing the push feature.

When you assign result[key] = value;, essentially you are pushing to the array at that specific position.

To rectify this, you should modify your code as follows:

function convertObjectToArray(obj) {
    const result = [];
    
    for (const [key, value] of Object.entries(obj)) {
        if (typeof value === 'object' && value !== null) {
            // push a spread of the array, this prevents nested arrays
            result.push(convertObjectToArray(value));
        } else {
            result.push(value);
        }
    }
    return result;
}

const initialData = {
    "1129931367": {
        "id": 10,
        "amount": 1,
        "assets": {
            "appid": 252490,
            "app_name": "name",
            "classid": 1129931367,
            "icon_url": "url",
            "tradable": 1,
            "name": "name",
            "market_name": "market name",
            "market_hash_name": "market hash name",
            "sell_listings": 3215,
            "sell_price": "0.10",
            "updated_at": "17-Dec-2022"
        },
        "market_tradable_restriction": 7,
        "market_marketable_restriction": 7,
        "tags": [
            {
                "category": "category",
                "internal_name": "internal name",
                "localized_category_name": "localized category name",
                "localized_tag_name": "localized tag name"
            },
            {
                "category": "category",
                "internal_name": "internal name",
                "localized_category_name": "localized category name",
                "localized_tag_name": "localized tag name"
            }
        ]
    }
}

console.log(convertObjectToArray(initialData))

UPDATE: Eliminated the spread operator for better functionality

Answer №2

To get a flat result, you can extract the values and use flatMap.

function convertObjectToArray(obj) {
    return Object
        .values(obj)
        .flatMap(value => value && typeof value === 'object'
            ? convertObjectToArray(value)
            : value
        );
}

const object = { "1129931367": { id: 10, amount: 1, assets: { appid: 252490, app_name: "name", classid: 1129931367, icon_url: "url", tradable: 1, name: "name", market_name: "market name", market_hash_name: "market hash name", sell_listings: 3215, sell_price: "0.10", updated_at: "17-Dec-2022" }, market_tradable_restriction: 7, market_marketable_restriction: 7, tags: [{ category: "category", internal_name: "internal name", localized_category_name: "localized category name", localized_tag_name: "localized tag name" }, { category: "category", internal_name: "internal name", localized_category_name: "localized category name", localized_tag_name: "localized tag name" }] } };

console.log(convertObjectToArray(object));
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Issue with jqGrid Multiple Selection

When constructing my jqgrid, I utilize the following code: multiselect: true This enables a check all column. However, clicking the check all checkbox (located at the header) selects all checkboxes, but does not click the checkboxes in each row. You can ...

Ensuring the successful execution of all AJAX calls (not just completion)

I've seen this question asked many times about how to trigger a function once all AJAX calls have finished. The typical solution involves using jquery.stop(). However, my situation is unique - I want to display a confirmation banner only after all AJA ...

Using Vue to iterate through elements

I am struggling to loop through an array in a Vue component without duplicating the element specified in the 'v-for' directive. I have consulted the official Vue.js API documentation, as well as various online articles, but haven't found a s ...

Utilizing ES6 promises in node.js to send a null response

I'm looking for assistance on how to execute a query using ES6 native promises in node.js. The code I have below is what I've been working with: let arr= []; conn.query('select * from table1', (err, b) => { for (let i = 0; i ...

Is there a way to emulate synchronous behavior in JavaScript?

var routeSearch = new MyGlobal.findRoutes({ originPlaceId: search.placeInputIds.originPlaceId, destinationPlaceId: search.placeInputIds.destinationPlaceId, directionsService: search.directionsService, directionsDisplay: sear ...

Guide to embedding bootstrap.min.js into ember-bootstrap extension

I'm currently experiencing an issue with the ember-bootstrap plugin. Following the instructions on their setup page at , I downloaded and installed it. Once I began working on the Navbar, I encountered a problem. The Hamburger menu, which is supposed ...

"Encountering a Type Error while attempting to destructure elements within ReactJS

Issue Upon querying objects from the GraphQl server and logging data, I can see the objects in the console. However, when attempting to destructure it as data: { getPosts : posts }, a type error is returned. Furthermore, trying to use map directly on data ...

What exactly does `(..)` represent in the Body(...) when extracting data from a POST request in FASTAPI?

I'm currently working on parsing the body of a POST request using FastAPI. Unfortunately, I'm having trouble grasping the meaning of the (...) argument in the Body function This is the code I have so far : @app.post('/createPosts') def ...

Change a 24-hour time variable to 12-hour time using AngularJS/jQuery technology

I have a value retrieved from the database in a 24-hour time string format. I am seeking a solution to convert this string into a 12-hour clock time using either AngularJS or jQuery. Currently, I am unable to make any changes to the back-end (JAVA) or the ...

Using JQuery to specify an attribute as "required" along with a value does not function as expected

Something seems off with this: $("#elementId").attr("required", "true"); In Chrome and Firefox, the DOM either displays required as the attribute (with no value) or required="" (empty value). Interestingly, it doesn't make a difference what value w ...

Typescript is throwing a fit over namespaces

My development environment consists of node v6.8.0, TypeScript v2.0.3, gulp v3.9.1, and gulp-typescript v3.0.2. However, I encounter an error when building with gulp. Below is the code snippet that is causing the issue: /// <reference path="../_all.d. ...

The request is not functioning as expected for some reason

My current challenge involves retrieving photos from Instagram using a GET request. I attempted to use jQuery.get(), which has been successful for other types of GET requests but not for Instagram. Despite trying to switch to jQuery.getJSON(), the issue pe ...

What is the significance of utilizing app.set() and app.get() in applications?

Is there a way to simplify this code: app.set('port', (process.env.PORT || 3000)); const server = app.listen(app.get('port'), () => { console.log('Server|Port: ', app.get('port')); }); Here is an alternative ...

Why is there a CSS reference failure in Express and how can it be resolved?

Below, you'll find a simple express server I've put together: // check out my basic Express server var express = require("express"); var app = express(); var bodyparser = require("body-parser"); app.use("/public/", express.static("./public/")); ...

Place content following a three.js display created within a <div id="mainWindow">

Recently, I created a small Three.js animation and embedded it in my HTML page like this: <div id="mainWindow" class="popup_block"> <!-- JavaScript for simulation --> <script src="../temp/webgl-debug.js"></script> <scri ...

Refreshing the access token in Linkedin's oauth does not result in extending the expiration time

Currently, I am implementing a strategy to renew Linkedin OAuth2 access tokens. When starting the OAuth process in the browser, the dialogue is skipped and a new code is generated. This code is then used to acquire a fresh access_token that differs from t ...

What is the best way to run a lengthy task in Node.js by periodically checking the database for updates?

In my current setup, there is a routine that continuously checks the database for any pending work orders. Upon finding one, it needs to execute it promptly. The system can handle only one work order at a time, and these tasks may vary in duration from 5 s ...

Guide on converting JSON object to condensed rows when using ng-repeat

From the database, I am receiving a JSON object which is one large object: $scope.totalsum = { "A1": 1155000, "A2": null, "A3": 2133, "A31": 29292, "A32": 2321, "A33": 232342, ...

Dynamic arrays in the C programming language allow for efficient memory

As I attempt to populate an array using fscanf() while iterating through a file filled with a series of integers, each n integers in length, I have come to realize that I may need to utilize malloc and/or possibly realloc. I have read that the malloc funct ...

404 error occurs when AngularJS removes hash symbol from URLs

I successfully eliminated the hash from my Angular JS website using the following code snippet: $locationProvider.html5Mode(true); Now, the previously displayed URL has been replaced with . The issue I'm facing is that when I do a hard refresh (Ct ...