У меня есть этот массив:
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.info(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.info(check);
@PedroBarreto Это не ожидаемый результат. ОП хочет один объект с двумя свойствами.
Кажется хорошим кандидатом на 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.info(result);
не могли бы вы объяснить, почему не рекомендуется просто распространять результат?