Question:
Sorry if I cant summarize the problem in a nut shell, so I try to explain it in details.
I try to construct a object by using a input. However my consolidated results containing only one item, while expecting to have more than one.
Q2:In addition to the bug, may I seek for a answer that could avoid issue with array manipulation when I try to copy value from one array to a new variable, then change the value in it?
Problem:
Input:
[ { name: 'Balanced',
allocations: [ [Object], [Object], [Object] ] },
{ name: 'Balanced Plus',
currency: 'GBP',
allocations: [ [Object], [Object], [Object] ] },
{ name: 'Conservative',
currency: 'GBP',
allocations: [ [Object], [Object], [Object] ] },
{ name: 'Growth',
currency: 'GBP',
allocations: [ [Object], [Object], [Object] ] },
{ name: 'Income',
currency: 'GBP',
allocations: [ [Object], [Object], [Object] ] } ]
Expected output:
{ US: { allocation: { Balanced: [Array] , Balanced Plus: [Array], Conservative: [Array], Growth: [Array], Income: [Array]} } }
Result:
{ US: { allocation: { Income: [Array] } } }
Below is my present code:
const a = [
{
name: "Balanced",
allocations: [
{
id: "2241",
},
{
id: "1175",
},
{
id: "2269",
},
],
},
{
name: "Balanced Plus",
currency: "GBP",
allocations: [
{
id: "2238",
},
{
id: "1175",
},
{
id: "2269",
},
],
},
{
name: "Conservative",
currency: "GBP",
allocations: [
{
id: "2241",
},
{
id: "1175",
},
{
id: "2300",
},
],
},
{
name: "Growth",
currency: "GBP",
allocations: [
{
id: "2241",
},
{
id: "1175",
},
{
id: "2269",
},
],
},
{
name: "Income",
currency: "GBP",
allocations: [
{
id: "2241",
},
{
id: "1175",
},
{
id: "2300",
},
],
},
];
console.log(a);
const trans = (a) => {
const result = a.reduce((pre, cur) => {
const allocation = { [cur.name]: cur.allocations };
return { ...pre, allocation };
}, {});
return result
};
const b = { US: trans(a) };
console.log(b);
>Solution :
Here I’ve turned "US.allocation" into an object with property names like "Balanced", "Conservative" etc, with the appropriate allocations array as the property value.
const a = [
{
name: "Balanced",
allocations: [
{
id: "2241",
},
{
id: "1175",
},
{
id: "2269",
},
],
},
{
name: "Balanced Plus",
currency: "GBP",
allocations: [
{
id: "2238",
},
{
id: "1175",
},
{
id: "2269",
},
],
},
{
name: "Conservative",
currency: "GBP",
allocations: [
{
id: "2241",
},
{
id: "1175",
},
{
id: "2300",
},
],
},
{
name: "Growth",
currency: "GBP",
allocations: [
{
id: "2241",
},
{
id: "1175",
},
{
id: "2269",
},
],
},
{
name: "Income",
currency: "GBP",
allocations: [
{
id: "2241",
},
{
id: "1175",
},
{
id: "2300",
},
],
},
];
const b = {
US: {
allocation: Object.fromEntries(a.map(el => [el.name, el.allocations]))
}
};
console.log(b);