I'm struggling with the following javascript problem. Is there any way to do it like this?
// input, based on this data, I want the output to be like below
const ListValues = ["id", "name", "description"]
// output
const initialValues = {
id: "",
name: "",
description: "",
};
Thank you so much and Have a good day <3
You can use Object.fromEntries() and Array.map() to create your desired object from the input.
const ListValues = ["id", "name", "description"];
const initialValues = Object.fromEntries(ListValues.map(v => [v, '']));
console.log('initialValues:', initialValues)
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could also use Array.reduce() to get the same result:
const ListValues = ["id", "name", "description"];
const initialValues = ListValues.reduce((acc, cur) => {
acc[cur] = '';
return acc;
}, {})
console.log('initialValues:', initialValues)
.as-console-wrapper { max-height: 100% !important; top: 0; }