Home > Enterprise >  How to loop through an array an put create an array of objects using react and javascript?
How to loop through an array an put create an array of objects using react and javascript?

Time:01-24

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.

CodePudding user response:

Use Array.map:

const array = [
  "first",
  "second",
]

const res = array.map(e => ({
  label: e,
  value: e
}))
console.log(res)

CodePudding user response:

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)

  •  Tags:  
  • Related