-1

Need help for converting an array to array of object adding label.

For example I have an array:

data = ["data1", "data2", "data3"]

I want to convert and adding label. The result expected:

[
   {label: "data1", value: "data1"},
   {label: "data2", value: "data2"},
   {label: "data3", value: "data3"}
]
2
  • use map and inside the map return {label: e, value: e} where e is the each iteration in map Commented Nov 9, 2022 at 6:07
  • stackoverflow.com/questions/58334039/… Commented Nov 9, 2022 at 6:09

3 Answers 3

4

Just using data.map(d => ({label:d,value:d})) can do it

let data = ["data1", "data2", "data3"]

let result = data.map(d => ({label:d,value:d}))

console.log(result)

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

Comments

1
const data = ["data1", "data2", "data3"];
const object = [];
data.forEach((element) => {
  const obj = { label: element, value: element };
  object.push(obj);
});
console.log(object);

Comments

0

You can achieve it using multiple ways, below is an implementation using reduce

let data = ["data1", "data2", "data3"];
let result = data.reduce((acc, item) => {
   acc.push({label: item, value: item});
   return acc;
   }, []);
console.log(result);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.