What is the best way to transform Object keys into an array containing elements repeated based on their corresponding key values in Javascript?

For example

object = {x:5, y:2, z:3}

The converted output will be:

['x','x','x','x','x','y','y','z', 'z', 'z']

Answer №1

Retrieve data elements and create a flattened map with an array of a specified length, then populate the array with the corresponding key.

const
    object = { x: 5, y: 2, z: 3 },
    result = Object.entries(object)
        .flatMap(([key, value]) => Array(value).fill(key));

console.log(result);

Answer №2

One way to achieve this is by utilizing the reduce method in JavaScript:

const data = {apple: 3, banana: 2, cherry: 1};

const result = Object.keys(data).reduce((arr, key) => {
  return arr.concat( new Array(data[key]).fill(key) );
}, []);

console.log(result); // ["apple", "apple", "apple", "banana", "banana", "cherry"]

Explanation:

  • The Object.keys() method generates an array of all keys from the object: ["apple", "banana", "cherry"]

  • We iterate over each key using reduce, creating a new array for each key based on its value. We fill this array with the respective key (apple, banana, etc.).

  • Finally, we concatenate these arrays together using concat.

Answer №3

Give this a shot:

let myObj = { x:5, y:2, z:3 }
let newObjs = [];

for (var keys in myObj) {
  while (myObj[keys]) {
    newObjs.push(keys);
    myObj[keys]--;
  }
}

console.log(newObjs);

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

Error: Module 'fs' does not export the function 'existsSync' as requested

When I simulate the behavior of the fs module jest.mock('fs', () => { return { default: { readFileSync: () => { return CONTENT_DATA; }, existsSync: () => {}, }, }; }); Then I attempt to dynamically ...

You cannot define headers once they have been sent to the client. If you encounter a NextJS redirect issue, consider using res

I encountered an error when redirecting to a link from NextJS -> _app.js -> getInitialProps. I am trying to cache the last user language in cookies and redirect to it when the page is reloaded. It's working and the user is redirected, but I&apos ...

Using axios to make a request to a REST API

I recently developed a Rest API using express to interact with mongodb. Testing it with postman has been successful so far. However, when I attempted to integrate the api with a basic web app created in vue and used axios to get a response from the api, ...

Retrieving data efficiently: utilizing caching in an AngularJS service to store data fetched from a single $http request

Forgive me if this question seems simple or silly, but I find myself in a new scenario and need some guidance. In my AngularJS app, I have a service with 4 methods that share about 80% of the same functionality and code. I want to optimize this and make it ...

retrieving data from a different controller in AngularJS

Having an issue with passing data from rootScope.reslogin2 to scope.user. It's not displaying as expected, here is my JavaScript file: app.controller("logincont", ['$scope','$http','md5','$window','$rootS ...

Is there a way to detect duplicate usernames in a form without actually submitting the form, and then automatically focus on the username field if a duplicate is

I need help with a user registration form that I am creating. I want the form to automatically search for an existing username as soon as the user starts typing in the username field. If the username already exists, I want the field to receive focus. In my ...

The user's input does not properly match with the elements in the array

I'm currently working on my first code project and I've encountered an issue with a specific piece of code. My goal is to compare a user's input with an array to check if the input choice is present in the array and then add the input to a v ...

Erase all records using MongoDB by the following criteria or

I am currently working with a calendar document structured as shown below: calendar: [ {days: { 1: [], 2: ['surprise'], 3: [], ... }}, {days: { 1: [], 2: [], 3: ['test'], ... }} ] My task involves locating specific ...

Angular protection filter

Every time I used Angular CLI to generate a new component, it would create the component with standard parameters: @Component({ selector: 'app-test1', templateUrl: './test1.component.html', styleUrls: ['./test1.component.css ...

The React implementation of an OpenLayers map is not responsive on mobile devices

I recently set up an OpenLayers map in a React project and it's working smoothly on desktop browsers. The map is interactive, allowing users to drag, zoom in/out, and display markers as expected. However, I'm facing an issue with touch events on ...

unable to show image retrieved from JSON data

Looking to showcase the data from my JSON objects, which are displayed in 2 images below https://i.stack.imgur.com/yhqFy.png https://i.stack.imgur.com/DUgFO.png In the data, I have properties like c_name, max_slots, and an array slots. Within the array, ...

Iterate through the URL parameters and store them in the database

I need to efficiently loop through all my post requests and aggregate them collectively. What is the most effective approach for achieving this? Below is the Form structure along with the data I receive: var Form = new Schema({ title: { type: ...

Error with 'Access-Control-Allow-Origin' while making a request using JavaScript

In the process of creating my angular 2 application, I've implemented a module known as github-trend. Within this setup, there is a service that interacts with various functions from the module. scraper.scrapeTrendingRepos("").then(function(repos) { ...

Two interactive dropdown menus featuring custom data attributes, each influencing the options available in the other

Looking to create interactive select boxes based on the data attribute values? This is the code I currently have: HTML <select id="hours" onchange="giveSelection()"> <option value="somethingA" data-option="1">optionA</option> <o ...

Leveraging findOne and findOneAndUpdate with an HTTP request in mongoose

I am currently developing an API Rest where I need to make HTTP requests using Postman. Specifically, I am trying to search for or update a MongoDB document by an ID that is not the default doc_id provided by Mongo. Models Schema 'use strict' ...

establish the data type for the key values when using Object.entries in TypeScript

Task Description: I have a set of different areas that need to undergo processing based on their type using the function areaProcessor. Specifically, only areas classified as 'toCreate' or 'toRemove' should be processed. type AreaType ...

The animation in Material UI does not smoothly transition with the webkit scrollbar

I've been experimenting with CSS animations in Material UI's sx property to achieve a webkit scrollbar that eases in and out. However, instead of the desired effect, the scrollbar appears and disappears instantly. Whether I define the keyframes ...

What are the best methods for creating genuinely random and highly secure session IDs?

I am looking to develop session middleware for Express, however, I am unsure about generating random and secure session IDs. How do larger frameworks like Django and Flask handle this issue? What would be the best approach for me to take? ...

What is the method for determining the mean value of items in a three-dimensional array?

I am attempting to calculate the average value for certain parameters and then create a plot using a predefined function. My plan is to populate a 3-column array with values, take the average of those values, and then plot them after creating 1000 values f ...

Use two arrays to retrieve a value from the second array

I am facing a challenge involving two arrays. The arrays in question are named $queue_ids and $subscriber_results. The array $queue_ids displays: Array ( [0] => 3 [1] => 4 [2] => 5 ) On the other hand, $subscriber_results exhibits: Array ( [ ...