1

For example I have this Array:

 const arr = [
    {val1: '123', text: 'not a num', new:'123.34'},
    {val1: '123', text: 'not a number', new:'123.34'},
    {val1: '123', text: 'yahoo', new:'123.34'}
    ]

And I want to convert the keys val1 and new into a number,

so I created this function:

const convertToNumbers = (arr: Array<{ unknown }>, keys: Array<string>) => {
  return arr.map((val) => {
    keys.map((k) => {
      console.log(val[k]);
      return (val[k] = +val[k]);
    });
   
  });
};

Expected result should be like this:

   const result = [
        {val1: 123, text: 'not a num', new:123.34},
        {val1: 123, text: 'not a number', new:123.34},
        {val1: 123, text: 'yahoo', new:123.34}
        ]

The function will accept both an Array(first param is the Array itself and the second contains the key to be converted into number).

Is there a way to solve my problem?

5
  • Do you want to do this in-place, or return a new array with copies of the objects with the appropriate keys converted? Commented Sep 3, 2020 at 11:55
  • You can use parseInt or parseFloat to do the conversion Commented Sep 3, 2020 at 11:56
  • new Array is better Commented Sep 3, 2020 at 11:56
  • If you're not interested in the return value of .map() (keys.map((k) => ...)) then .map() is the wrong tool Commented Sep 3, 2020 at 11:57
  • Does this answer your question? Converting array of objects value into integer value Commented Sep 3, 2020 at 12:03

2 Answers 2

2

You could map new objects and convert wanted keys.

const 
    array = [{ val1: '1,234', text: 'not a num', new:'123.34' }, { val1: '123', text: 'not a number', new:'123.34' }, { val1: '123', text: 'yahoo', new:'123.34' }],
    keys = ['val1', 'new'],
    result = array.map(object => ({
        ...object,
        ...Object.fromEntries(keys.map(key => [key, +object[key].replace(/[^\d.]/g, '')]))
    }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

3 Comments

I'm trying to delete the comma as well with this method [key, +object[key].replace(/,/g, '')] but with no luck
sorry I forgot to add in the example... For example 1,299 to 1299
you need a replacement of unwanted characters. please see edit.
0

const arr = [
    {val1: '123', text: 'not a num', new:'123.34'},
    {val1: '123', text: 'not a number', new:'123.34'},
    {val1: '123', text: 'yahoo', new:'123.34'}
    ]
var text = "";
var i;
for (i = 0; i < arr.length; i++) {
  text += arr[i].val1;
}
document.getElementById("demo").innerHTML = text;
<p id="demo"></p>

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.