Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I create an object based on the keys of an array?

I have this array:

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

Which I need to turn into this: { result: { [uuid-label]: number } }

result: {
 '123312-hello': 10 // this is just a random number for now
 '523312-there': 20
}

The code that I have so far is this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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]);

But that code above is creating an array, like [{'123312-hello': 10}, {'523312-there': 20}]

Check the code snippet:

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);

So what am I missing?

>Solution :

You can use reduce instead of map:

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.reduce((acc, o) => {
  acc[`${o.uuid}-${o.label}`] = randomIntFromInterval(0, 500);
  return acc;
}, {});

console.log(check);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading