0

I have an array like this:

const categories = ["Action", "Comedy", "Thriller", "Drama"]

And I would like to convert it to this format:

const displayedCategories = [{"type": "Action", "isDisplayed": true},{"type": "Comedy", "isDisplayed": true},{"type": "Thriller", "isDisplayed": true},{"type": "Drama", "isDisplayed": true}]

Any advice ? :)

AndrewL64
  • 15,794
  • 8
  • 47
  • 79
Elgur
  • 13
  • 1
  • 3
    What have you tried so far? – AndrewL64 Jan 12 '20 at 17:59
  • 1
    For a future reference check out how to ask a good question https://stackoverflow.com/help/how-to-ask. @AndrewL64 is right, you should provide at least what you have tried, otherwise you're just asking others to solve the problem for you. – SciFiThief Jan 12 '20 at 18:02

5 Answers5

0

You can do so by using map:

const categories = ["Action", "Comedy", "Thriller", "Drama"];

const newCategories = categories.map(category => ({
  type: category,
  isDisplayed: true
}));

console.log(newCategories);
Carl Edwards
  • 13,826
  • 11
  • 57
  • 119
0

You can do so with the map method:

const displayedCategories = categories.map(function(category) {
   return { type: category, isDisplayed: true };
});
mgarcia
  • 5,669
  • 3
  • 16
  • 35
0

Maybe like This:

const categories = ["Action", "Comedy", "Thriller", "Drama"];
var out = [];
for(var key in categories){
  out.push({"type": categories[key], "isDisplayed": true});
}
console.log(out);
mscdeveloper
  • 2,749
  • 1
  • 10
  • 17
0

use array.prototype.map to convert the array into an object

categories = catergories.map(val => {
  var obj =  {
    type:val
    //more properties go here
  }
  return obj
}
Raphael Castro
  • 907
  • 1
  • 8
  • 26
0

const categories = ["Action", "Comedy", "Thriller", "Drama"]
const displayedCategories = categories.map(category =>  { return {"type": category, "isDisplayed": true} })
console.log('displayedCategories :', displayedCategories);
Aldrin
  • 2,036
  • 15
  • 12