'Converting array of objects value into integer value
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}]
Solution 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
