reactjsarrayobjectnested-objectobject-object-mapping

reactjs - get a subset of an nested array objects


I have a variable like this, which I am passing as an input into the react app.

const options = [{"label": "Gryffindor", "value": "Gryffindor", "description": "Daring, strong nerve and chivalry.", "color": "#00ffa2"},
      {"label": "Slytherin", "value": "Slytherin", "description": "Cunning and ambitious. Possibly dark wizard.", "color": "#84d2ff"}]

From the above array i want to achieve the following output:

const TAG_COLORS:any = {
  Gryffindor: '#00ffa2',
  Slytherin: '#84d2ff',
}

can some one suggest how to achieve this?


Solution

  • Think this is what you are after:

    edit. my bad misread the question.

      const options = [{"label": "Gryffindor", "value": "Gryffindor", "description": "Daring, strong nerve and chivalry.", "color": "#00ffa2"}, {"label": "Slytherin", "value": "Slytherin", "description": "Cunning and ambitious. Possibly dark wizard.", "color": "#84d2ff"}];
     
    var TAG_COLOURS = {};
    for (var i = 0; i < options.length; i++) {
      TAG_COLOURS[options[i].label] = options[i].color;
    }
    
    console.log(TAG_COLOURS);