Reputation: 731
I have array of objects. Here is small amount of the data:
[
{
State: "AK",
AvgExpenseRatio: 0.46,
Test2: 2,
},
{
State: "AL",
AvgExpenseRatio: 0.67,
Test2: 3,
}]
I am checking if the data in Test2 is above 2 and if it is I am returning new object that depends on this data:
const temp = mapData.map((el) => {
return {
[el.State]: {
fill: el.Test2 > 2 ? "red" : "green",
},
};
});
After this data looks like:
[
0:{
AK:{
fill:'green'
},
1:{
AL:{
fill:'red'
}
}]
I want the final data to look like this:
const exampleShouldLook = {
AK: {
fill: "green",
},
AL: {
fill: "red"
}
};
Object with object which names are the states. How I can do that. Here is the sandbox example for more clear explain:
https://codesandbox.io/s/sad-sanne-ugmn4?file=/src/index.js
Upvotes: 1
Views: 100
Reputation: 8751
You can use array reduce()
const mapData = [
{
State: "AK",
AvgExpenseRatio: 0.46,
Test2: 2,
},
{
State: "AL",
AvgExpenseRatio: 0.67,
Test2: 3,
}]
const output = mapData.reduce((acc, val) => {
acc[val.State] = { fill : val.Test2 > 2 ? "red" : "green" }
return acc;
}, {});
console.log(output);
Upvotes: 1