reactjs - get a subset of an nested array objects

198 Views Asked by At

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?

2

There are 2 best solutions below

1
On BEST ANSWER

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);

0
On

You may use the map function to create a JavaScript object and then use the JavaScript object method on it.

This is how you may go about it:

var 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"}
]


options.map((data)=>{console.log(Object.values(data))})

Hope this answers your question