0

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

Four
  • 125
  • 1
  • 1
  • 9

1 Answers1

2

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; }
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
  • 1
    Thank you vary much, and I also just found more information here, hope it helps the following people https://stackoverflow.com/questions/54789406/convert-array-to-object-keys – Four Oct 20 '21 at 07:36