2

I want to convert this

const data = [
 {
   date: "2020-01",
   pageviews: "1548"
 },
 {
   date: "2020-01",
   pageviews: "2000"
 },
]

to

const data = [
 {
   date: "2020-01",
   pageviews: 1548
 },
 {
   date: "2020-01",
   pageviews: 2000
 },
]

but I can't find the a way. I want to use those data to Rechart and the pageviews need to be numbers not strings Can someone help me?

3 Answers 3

3

Solution

You can use forEach to loop over your array.
At each entry parse your pageviews to an int with parseInt()

const data = [
 {
   date: "2020-01",
   pageviews: "1548"
 },
 {
   date: "2020-01",
   pageviews: "2000"
 },
]

console.log(data);

data.forEach((val) => {
  val.pageviews = parseInt(val.pageviews);
});

console.log(data);

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

3 Comments

You're welcome :) if you think this was helpful you can mark this as accepted.
Using .map() instead of .forEach() to mutate the elements' properties is pretty weird.
True first I thought I create a new array but I didn't, have updated it.
0

<script>
  const data = [
 {
   date: "2020-01",
   pageviews: "1548"
 },
 {
   date: "2020-01",
   pageviews: "2000"
 },
]

 data.forEach(item => {
  item.pageviews = parseInt(item.pageviews)
  return item
 })
 
 console.log(data)
</script>

You can use the parseInt function of JavaScript to convert your String to a Number.

Comments

0

If you do not want to alter the original array, you can use Array#map with spread syntax.

const data = [
 {
   date: "2020-01",
   pageviews: "1548"
 },
 {
   date: "2020-01",
   pageviews: "2000"
 },
]
const res = data.map(({pageviews, ...rest})=>({...rest, pageviews: +pageviews}));
console.log(res);

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.