Reputation: 53
I am new to javascript/typescript. currently have an array of objects
I would like to convert the value to a integer. Currently I am mapping the value by
var k = [{key: "apples", value:"5"}, {key: "orange", value:"2"}];
var output = Object.entries(k).map(([key,value]) => ({key,value}));
console.log(output)
Expected output is
[{key: "apples", value:5}, {key: "orange", value:2}]
Upvotes: 2
Views: 1775
Reputation: 50684
There is no need to use Object.entries()
on your array, you can simply apply .map()
directly to your k
array. For each object, you can destructure it to pull out its value
property, which you can then map to a new object with the value
converted to a number using the unary plus operator (+value
) like so:
const k = [{key: "apples", value:"5"}, {key: "orange", value:"2"}];
const output = k.map(({value, ...rest}) => ({...rest, value: +value}));
console.log(output)
If you wish to change your array in-place, you can loop over it's object using a .forEach
loop, and change the value
using dot-notation like so:
const k = [{key: "apples", value:"5"}, {key: "orange", value:"2"}];
k.forEach(obj => {
obj.value = +obj.value; // use `+` to convert your string to a number
});
console.log(k)
Upvotes: 4