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

Time:04-05

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:

  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?

CodePudding user response:

Seems a good candidate for Object.fromEntries:

const randomIntFromInterval = (min, max) => Math.floor(Math.random() * (max - min   1)   min);
const options = [{uuid: '123312',label: 'hello'},{uuid: '523312', label: 'there'}];

const result = Object.fromEntries(options.map(({uuid, label}) =>
    [`${uuid}-${label}`, randomIntFromInterval(0, 500)]
));

console.log(result);

CodePudding user response:

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

  • Related