Converting an object with key-value pairs into a regular array in Javascript

Is there a better method to convert an associative array to a standard array with 0 based indexes other than manually iterating and rewriting each item?

I have an array that was generated by tallying the occurrences of certain properties and it needs to remain in that format. The current array structure is as follows:

let ASSARR = { 
    "abc": { "c": 5, "p": 3 },
    "def": { "c": 1, "p": 10 },
    "ghi": { "c": 15, "p": 7 }
};

...and so on. After filtering and sorting the array, I need to transform it into a standard array format like this:

let STARR = [
    { "i": "abc", "c": 5, "p": 3 },
    { "i": "def", "c": 1, "p": 10 },
    { "i": "ghi", "c": 15, "p": 7 }
];

Is there a more efficient way to accomplish this task without using a traditional loop such as for?

Answer №1

Is there a different method other than iteration and rewriting each item?

No, you will need to use a loop (either in your code, or in code in the standard library that you call such as looping through the result of Object.entries).

Since it involves a loop either way, I would recommend just writing the loop (especially because by doing so, you can loop just once instead of multiple times). Assuming you want to create new objects rather than simply adding an i property to the existing objects:

const result = [];
for (const i in ASSARR) {
    result.push({
        i,
        ...ASSARR[i],
    });
}

let ASSARR = { 
    "abc": { "c": 5, "p": 3 },
    "def": { "c": 1, "p": 10 },
    "ghi": { "c": 15, "p": 7 }
};
const result = [];
for (const i in ASSARR) {
    result.push({
        i,
        ...ASSARR[i],
    });
}
console.log(result);
.as-console-wrapper {
    max-height: 100% !important;
}

If you wish to modify the existing objects instead:

const result = [];
for (const i in ASSARR) {
    const object = ASSARR[i];
    object.i = i;
    result.push(object);
}

let ASSARR = { 
    "abc": { "c": 5, "p": 3 },
    "def": { "c": 1, "p": 10 },
    "ghi": { "c": 15, "p": 7 }
};
const result = [];
for (const i in ASSARR) {
    const object = ASSARR[i];
    object.i = i;
    result.push(object);
}
console.log(result);
.as-console-wrapper {
    max-height: 100% !important;
}


Note: The instructions assume that there are no inherited but enumerable properties that you want to exclude. If there are any, enclose the push calls in if (Object.hasOwn(object, i)) to skip inherited properties.

Answer №2

One way to retrieve the data is by extracting the entries and associating them with specific keys.

const
    object = { abc: { c: 5, p: 3 }, def: { c: 1, p: 10 }, ghi: { c: 15, p: 7 } },
    array = Object
        .entries(object)
        .map(([i, o]) => ({ i, ...o }));

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

Answer №3

To achieve this, simply utilize Object.entries along with Array.map...

For example...

let data = { 
    "apple": { "price": 2, "quantity": 10 },
    "banana": { "price": 1, "quantity": 20 },
    "orange": { "price": 3, "quantity": 5 }
};

let modifiedData = Object.entries(data).map(([key,value]) => {
  return {item: key, ...value};
});

console.log(modifiedData);

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

Click the "Add to Cart" button to make a purchase

Recently, I've been working on modeling an add to cart feature using jQuery. However, I have encountered a small issue that I'm trying to troubleshoot. When I click the mybtn button, the model displays and functions correctly, but there seems to ...

Objects shifting position as the browser window is resized or zoomed

I've scoured through numerous examples, but none seem to work for my specific situation. On my webpage, I have multiple tables nested within a <div>, which serves as a background element (as it doesn't cover the entire screen). However, whe ...

Error message for Joi when validating a nested array of objects

I have received user input from the client side and am performing backend validation using Joi. const Joi = require("joi") const schema = Joi.array().items( Joi.object().required().keys({ name: 'filter_list', value: Joi.array(). ...

Unexpected behavior when using padding on the left side of a vertical position

I can't seem to figure out a strange issue. I have a div containing multiple paragraphs, but when I adjust the padding left within the div to align all paragraphs to the left, they not only shift to the left but also move up as if I'm positioning ...

Choose a specific example using the class name in nicEdit

Is there a way to select an instance using nicEdit based on its class name rather than just its id? For example: <div class="myInstance1"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed magna dolor, faucibus ac, iaculis non, cursus et ...

The JSON data lacks compatibility with the usage of track by functionality

I am working on a project that involves three connected select menus. The first one displays series names, the second one displays chapter numbers belonging to the series selected in the first menu, and the third one displays page numbers belonging to t ...

The significance of the "? :" operator in JavaScript

These are the lines of code I am currently working with: toggleMore : function( $item, show ) { ( show ) ? $item.find('a.ca-more').show() : $item.find('a.ca-more').hide(); }, Could someone help me understand what this code does? ...

Transforming an array of objects into a new array containing the average numbers of each object

I'm working with an array that needs manipulation in order to use it as a data source for D3.js. The dataset looks like this: var data = [ {day: 1, month: 1, length: 100, year: 2010}, {day: 2, month: 1, length: 125, year: 2010}, {day: 3, mon ...

Switching the positions of the date and month in VueJS Datepicker

Recently, I have been utilizing the datepicker component from vuejs-datepicker. However, I encountered an issue where upon form submission, the date and month switch places. For instance, 10/08/2018 (dd/MM/yyyy) eventually displays as 08/10/2018, leading ...

Exploring the Ability to Loop Through 3D Elements Using JavaScript

I'm new to using Three Js and I have a question about changing object positions. In my code, when the Button +1 is clicked, the object moves after 1 room. Now, I want it so that when Button +2 is clicked, the object changes position after 2 rooms ins ...

I'm interested in finding out how to utilize the bezierjs library. Can someone

I am working with a canvas drawing that features various curves, and I am curious about determining its size similar to a specific example in this library. Check out the library here For reference, take a look at this example: Curve Size Example I would ...

Chartjs tooltips are displayed across all charts when hovering over a single chart

Currently, I am utilizing ChartJS in conjunction with angular. I successfully implemented a vertical line on my chart when hovering by following the example provided at How to render a vertical line on hover in chartjs. Now, I am seeking examples for crea ...

What is the most effective method for locating the row indices of numerous elements within a 2D matrix?

Could you help me find a more efficient way to retrieve the row indices from a list of arrays in Python? C = [ [1,2,3],[1,3,4],[3,5,6]] item_list=[1,3,4] I tried using the following code snippet: rind = [[i for i in range(len(C)) if item in C[i]] ...

What is the reason behind the for of loop breaking within an async function instead of properly awaiting the execution?

Update 2: I made changes to use setTimeOut instead, which fixed the issue. Check out the accepted answer for details on what was causing the error. The code below is now functioning properly. async function getSlices() { const imgBuffs = await sliceImg ...

Can you guide me on how to access an Angular route using a URL that includes query parameters?

Within my current development project, I have implemented a user profile route that dynamically navigates based on the user's _id. This means that when a user accesses the page, their _id is stored in localStorage and then used to query MongoDB for th ...

Is there a way to merge arrays in jQuery by pushing one array into another?

I am looking to construct an array as shown below. var coordinates = [ [41.02178, 29.26108], [41.02196, 29.26067], [41.02251, 29.26031], [41.02258, 29.26015], [41.02267, 29.25926] ]; My attempt in the code was as follows: var locations = []; f ...

Replace the arrow and implement collapsible div using CSS

My HTML code has the following structure: <ul id="urlcss"> <li class="nav-submenu"> <a class="collapsed" href="#" data-toggle="collapse" data-target="#submenu0"> ...

Creating a JavaScript/jQuery array containing values from multiple input fields

Having trouble figuring out a simple question. I want to create a JavaScript array of input values, but can't seem to get the code right. Below is the HTML: <input class="email" value="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Troubleshooting Error: Heroku, mLab, and Node.js - Application Issue with Mongoose

As a beginner in the world of Node.js and Heroku, I am attempting to host my first application on Heroku but encountering deployment issues. To guide me through this process, I have been following a tutorial which can be found here: https://scotch.io/tutor ...

Tips for managing onClick events within a conditional component

I am currently attempting to implement an onClick event on the data that I have selected from the AsyncTypeahead. My goal is to pass a callback function to the Problem component, which will only render if an item has been selected. However, after selecting ...