Sorry if the title is misleading I'm not sure how to accurately describe what I am looking for.
I have an array result
which I want to turn into multiple objects where each objects property is the field Name Test
I need to keep my result.map method as I use it to merge result
with data
result = [{
"Name Test": "Yellow",
Count: 124,
},
{
"Name Test": "Black",
Count: 124,
},
{
"Name Test": "Blue",
Count: 124,
}
];
data = [{
"Name Test": "Yellow",
pop: 1
},
{
"Name Test": "Black",
pop: 1
},
{
"Name Test": "Blue",
pop: 1
}
];
result = result.map((obj1, index) => {
const obj2 = data[index];
return {
[obj1["Name Test"].toUpperCase()]: {
Count: obj1.Count,
pop: obj2.pop,
}
};
});
console.log(JSON.stringify(result))
This code returns an array of objects which is not what I want as I need to be able to use result["YELLOW"]
later in my code. I therefore need the result to be in this format, with no arrays.
{
"YELLOW":{
"Count":124,
"pop":1
},
"BLACK":{
"Count":124,
"pop":1
},
"BLUE":{
"Count":124,
"pop":1
}
}
I hope this makes sense and I feel I am very close to what I want and just am missing something small, but every way I have tried to make this work turns into a syntax error.
map()
will always return an array.
You should use reduce()
and set accumulator to empty object {}
Use the destructuring and spread syntax to isolate Name Test
and other properties.
Set the property of accumulator whose key is "Name Test"
property of each object and its value is rest of the object.
const arr = [{ "Name Test": "Yellow", Count: 124, pop: 1 }, { "Name Test": "Black", Count: 124, pop: 1 }, { "Name Test": "Blue", Count: 124, pop: 1 } ];
const res = arr.reduce((ac,{["Name Test"]:x,...rest}) => (ac[x] = rest,ac),{})
console.log(res)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With