1

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.

2 Answers 2

1

Use Array.map:

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

thanks how can i check if array is null or undefined before mapping? i get error object could be possibly null | undefined.
@stackuser You can wrap the map in an if statement: if (array != null){ /* map */ }
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.