i want to loop through an array elements and create an array of objects with its values.
below is the array example which comes from querying from an api.
const array = [
"first",
"second",
]
now i want to create an array of objects like below
const arr_obj = [
{
label: "first",
value: "first",
}
{
label: "second",
value: "second",
}
]
i have tried like below
const arr_obj = React.useMemo(() => {
const output = arr.forEach(item => { //error
return {
label: item,
value: item,
}
}, [arr]});
but this gives error arr could be possibly undefined or null and also i think this is not the way to create an array of objects with label, value pairs from the array elements.
could someone help me with this. thanks.
Why not try this one?
const array = [
"first",
"second",
]
let arr_obj = []
for (let i in array) {
arr_obj.push({
label: array[i],
value: array[i],
})
}
console.log(arr_obj)