如何根据数组的键创建对象?

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

我有这个数组:

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

我需要把它变成这个:{ result: { [uuid-label]: number } }

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

我目前的代码是这样的:

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

但是上面的代码正在创建一个数组,例如 [{'123312-hello': 10}, {'523312-there': 20}]

检查代码片段:

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

那我错过了什么?

您可以使用 reduce 而不是 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);

似乎是 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);