2

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}]
2
  • Can you please show us an example of what your desired output would be for your input provided above? Commented Aug 26, 2019 at 11:16
  • my desired output would be [{key: "apples", value:5}, {key: "orange", value:2}]. i tried parsing it as a integer but it complained that it could not be converted and i am confused about it Commented Aug 26, 2019 at 11:17

1 Answer 1

4

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.