What is the best way to generate an object using the elements of an array as keys?

Consider the following array:

const options = [
    {
        uuid: '123312',
        label: 'hello'
    },
    {
        uuid: '523312',
        label: 'there'
    }
];

We want to transform it into this format:

{ result: { [uuid-label]: number } }

result: {
 '123312-hello': 10 // placeholder random number
 '523312-there': 20
}

Our current code snippet is as follows:

  const randomIntFromInterval = (min: number, max: number) => Math.floor(Math.random() * (max - min + 1) + min);

  const [result, setResult] = useState<Result>({} as Result);

  useEffect(() => {
    if(options.length) {
      setResult(
        options.map(o => {
          return { [`${o.uuid}-${o.label}`]: randomIntFromInterval(0, 500) }
      }))
    }
  }, [options]);

However, the above code produces an array like this:

[{'123312-hello': 10}, {'523312-there': 20}]

Here is a simplified version of the code for clarity:

const options = [{
    uuid: '123312',
    label: 'hello',
    sortOrder: 0
  },
  {
    uuid: '523312',
    label: 'there',
    sortOrder: 1
  }
];

const randomIntFromInterval = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

const check = options.map(o => {
  return {
    [`${o.uuid}-${o.label}`]: randomIntFromInterval(0, 500)
  }
});

console.log(check);

What adjustments are needed to achieve the desired outcome?

Answer №1

This code snippet is a great example of utilizing the Object.fromEntries method:

const generateRandomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
const items = [{id: '123312',name: 'apple'},{id: '523312', name: 'banana'}];

const result = Object.fromEntries(items.map(({id, name}) =>
    [`${id}-${name}`, generateRandomNumber(0, 100)]
));

console.log(result);

Answer №2

If you want to replace map with reduce, consider the following example:

const items = [{
    id: '123312',
    name: 'apple',
    quantity: 5
  },
  {
    id: '523312',
    name: 'banana',
    quantity: 10
  }
];

const generateRandomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

const result = items.reduce((acc, item) => {
  acc[`${item.id}-${item.name}`] = generateRandomNumber(0, 100);
  return acc;
}, {});

console.log(result);

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

Troubleshooting: JQuery dropdown selection not updating image display

I am trying to create a select menu that changes the car image when a user selects a different model, but for some reason it is not working. Here is what I have tried: <h2 class="model">A6 <img src="images/3.jpg" id="image" width="544" height="2 ...

Utilize custom SMTP with JavaScript to dispatch emails

I'm wondering if it is possible to send emails using just JavaScript (I am working on a PhoneGap app). I envision a scenario where I can connect to a specific SMTP server with a login and password, and then send emails using that connection. I have al ...

Create a function that outputs an array containing objects as its elements

Struggling with this one, I've hit my head against all corners but something seems to be missing. Details I'm working on a small JavaScript page that retrieves a Facebook photo ID, calculates the total number of people who shared it, identifies ...

Tips for simulating a decorator function applied to a method used in the system under test using JEST

I currently have a typescript class setup like this: export class SystemUnderTest { @LogThisAction('something was done') public doSomething() {} } It is clear that reflection is being used to execute a specific decoration function: exp ...

Issue: ENOENT - The file or directory does not exist. uv_chdir encountered an error when attempting to create a directory and navigate into it

I am facing a challenge while developing a small application that installs files and modules in a new folder. The error I keep encountering is: { Error: ENOENT: no such file or directory, uv_chdir at process.chdir (/home/aboardwithabag/LaunchProject/n ...

Identify the moment a dialogue box appears using jQuery

I'm facing a situation where multiple dialogs are opened in a similar manner: $("#dialog").load(URL); $("#dialog").dialog( attributes, here, close: function(e,u) { cleanup } The chall ...

Unable to get HTML text input validation with RegEx to function, despite incorporating the required attribute

I am attempting to create dynamically generated text inputs that only allow for digits and an optional decimal point. I have added the required attribute but the inputs are not responding to the RegEx pattern. var howMuch = $("<input>").attr("type", ...

What is the method to modify the hover background color and click background color for a dropdown item using Bootstrap Vue?

Hovering over the dropdown will change its background color to a light gray. The code below shows the dropdown in a navbar. <b-nav-item-dropdown text="TOOLS" right> <b-dropdown-item href="#" class="dropdown-mine">1</b-dropdown-item> ...

Enhance your WordPress menu with additional attributes

Currently, I am implementing a lightweight lightbox script on my WordPress website. My goal is to have one of the main navigation buttons open a Vimeo link in the lightbox. According to the lightbox documentation, I need to "Add the 'data-lity' a ...

Guidance on implementing a source map in a Node.js VM

Currently, I am analyzing JavaScript bundled source code in Node.js using the following snippet of code: const javascriptCode = "..." const javascriptSourceMap = "..." const wrapper = NativeModule.wrap(javascriptCode); const script = ne ...

Display information using HTML elements within a loop in JavaScript

I am facing an issue with iterating over an array of objects in JavaScript. Each object contains multiple parameters, and my goal is to extract the data from each object and display it in a table or a grid format. Here is an example of my code: function ...

Featuring the latest updates on the settings page

I am currently designing a settings page for my planning poker app. I want the additional settings to be visible only if the "become scrum master" checkbox is checked. I have tried using ng-show but it's not working as expected. Here is my code snippe ...

The precision of the stopwatch is questionable

Just starting out with JS and jquery, I quickly put together a stopwatch code in JS that seems to work accurately up to 10 minutes. The issue arises after the 10-minute mark where it starts falling a few seconds behind (I compared it to a digital stopwatc ...

What is the method of adding a child to the outerHTML of the parent element instead of within it?

Is there a way to use the outerHTML method on a parent element to append a child element so that the icons appear outside of the targeted element rather than inside it? The current code snippet shows the icons inside the box, but I want them to be placed o ...

A computed property declared inside a Vue component definition

I'm currently diving into Vue.js 2 and I have a goal of crafting a unique custom component in the form of <bs-container fluid="true"></bs-container>. My intention is for Vue.component() to seamlessly handle the bootstrap 3 container classe ...

Issues have been identified with the capabilities of Vue's Mutations and Actions

My Index.js from the Store Folder import Vue from "vue"; import Vuex from "vuex"; import state from "../store/state"; import mutations from "../store/mutations"; import actions from "../store/actions"; Vu ...

Sorting in Vuejs fails to function properly when a filter is applied

Having recently delved into Laravel and Vue, I am eager to develop a site for our Intranet. Pulling data from the Laravel database has been successful, displaying the data works well, and the search functionality is also up and running smoothly. However, I ...

Parsing PHP array using JavaScript

$namesSelect = "SELECT username FROM users"; $names = mysql_query($namesSelect); $nameCheck = mysql_fetch_array($names) This code snippet retrieves all usernames from the users table and stores them in the $names array. I am now faced with the task of ...

Retrieve a key from the JSON response and then transmit it through a socket

In the context of a node server code using a monitoring module to track function properties, I am facing an issue where I need to retrieve a specific property from a JSON output and then transfer it to a socket. The function 'meter' looks like t ...

Ways to verify that a ray does not intersect the face further

My approach involves creating cubes and rectangles on my scene with userData that initially have all 6 parameters set to "false". I then cast a ray from each face and if it intersects with another object's face, I set that specific face's paramet ...