I have an array of objects. I want to multiply GDPAnn by 10**6.
var Annual = [{"Date":1998,"Value":4.5,"GDPAnn":9062800},{"Date":1999,"Value":4.8,"GDPAnn":9631200},{"Date":2000,"Value":4.1,"GDPAnn":10251000},{"Date":2001,"Value":1,"GDPAnn":10581900}]
The code below returns only transformed GDPAnn. I want the similar array as above within transformed values of GDPAnn.
Annual.map((o) => o.GDPAnn * 10**6)
For a shorter way other than making a whole function body and return statement, you can (ab)use the comma operator:
Annual.map((o) => (o.GDPAnn *= 10**6, o))
The comma operator evaluates its left operand and evaluates its right operand, then gives you the value of the right operand.
In this case, we use it to multiply o.GDPAnn and then return o after we are done.
simply change your code into this
var Annual = [
{ Date: 1998, Value: 4.5, GDPAnn: 9062800 },
{ Date: 1999, Value: 4.8, GDPAnn: 9631200 },
{ Date: 2000, Value: 4.1, GDPAnn: 10251000 },
{ Date: 2001, Value: 1, GDPAnn: 10581900 },
];
Annual.map((o) => {
o.GDPAnn = o.GDPAnn * 10 ** 6;
return o;
});
console.log("Annual", Annual);
// [
// { Date: 1998, Value: 4.5, GDPAnn: 9062800000000 },
// { Date: 1999, Value: 4.8, GDPAnn: 9631200000000 },
// { Date: 2000, Value: 4.1, GDPAnn: 10251000000000 },
// { Date: 2001, Value: 1, GDPAnn: 10581900000000 }
// ]
It looks like you aren't assigning the result of your map() call to anything in which case you should be using a forEach() or a simple loop to mutate the original array.
const Annual = [{ "Date": 1998, "Value": 4.5, "GDPAnn": 9062800 }, { "Date": 1999, "Value": 4.8, "GDPAnn": 9631200 }, { "Date": 2000, "Value": 4.1, "GDPAnn": 10251000 }, { "Date": 2001, "Value": 1, "GDPAnn": 10581900 }]
for (const o of Annual) {
o.GDPAnn = o.GDPAnn * 10 ** 6
}
console.log(Annual);
If instead you actually do want to return a new array (as map() intends) then you should probably be cloning each object to avoid mutation in the original array. (Here using spread syntax (...) to clone each object and then providing the updated value for GDPAnn)
const Annual = [{ "Date": 1998, "Value": 4.5, "GDPAnn": 9062800 }, { "Date": 1999, "Value": 4.8, "GDPAnn": 9631200 }, { "Date": 2000, "Value": 4.1, "GDPAnn": 10251000 }, { "Date": 2001, "Value": 1, "GDPAnn": 10581900 }];
const updatedAnnual = Annual.map(o => ({ ...o, GDPAnn: o.GDPAnn * 10 ** 6 }));
console.log(updatedAnnual);