I have an array like this:
a1=[
{
"Domain": "xyz",
"Classification": "prod",
"AnnualData": [
{
"Year": 2029,
"Value": 67007.41
},
{
"Year": 2030,
"Value": 163234.6
},
{
"Year": 2031,
"Value": 166388.91
}
]
},
{
"Domain": "xyz",
"Classification": "prod",
"AnnualData": [
{
"Year": 2029,
"Value": 67007.41
},
{
"Year": 2030,
"Value": 163234.6
},
{
"Year": 2031,
"Value": 166388.91
}
]
}
];
I want to replace AnnualData , so that o/p look like
[
{
"2029": 67007.41,
"2030": 163234.6,
"2031": 166388.91,
"Domain": "xyz",
"Classification": "prod"
},
{
"2029": 67007.41,
"2030": 163234.6,
"2031": 166388.91,
"Domain": "xyz",
"Classification": "prod"
}
]
how would we do this?
I hava converted the annualdata into hashmap using list.reduce((obj, item) => ({…obj, [item.Year]: item.Value}), {});and tried to push it into main array but dint get the expected results
3
Answers
You don’t use
push()
to modify an object. You can useObject.assign()
to merge objects in place, or reassign using spread notation.I would have done it using forEach method, like this :
The principe is to create a new objet, and iterate over your data to fill the new object resulting as what you want.