Home > Net >  I want to Convert array into Custom Object
I want to Convert array into Custom Object

Time:03-07

I have array of Strings like this: let arr = ['HTML', 'CSS', 'JAVASCRIPT']

I have converted this array into an object using {...arr} method and the result is: { 0: "HTML", 1: "CSS", 2: "JAVASCRIPT" } I want this result in this format because I am using Fluent UI react dropdown and there inside options, we have arrays of objects having their own key and text. But I did not understand How do I customize my object like this -->

[
 {key: "HTML", text: "HTML"},
 { key: "CSS", text: "CSS" },
 { key: "JAVASCRIPT", text: "JAVASCRIPT" }
]

CodePudding user response:

JavaScript's Array.map() method is meant for a task like this. See this MDN page for details.

Below is an example solution for your needs.

const arr = ['HTML', 'CSS', 'JAVASCRIPT'];

const obj = arr.map(item => {
  return { key: item, text: item}
});

console.log(obj);

  • Related