Search code examples
javascriptlodash

Convert object property numeric value to string and append to object as new key value


0: {Number: 1 }
1: {Number: 2 }

I am using lodash and react. I cant convert the number to a string but not add the value back into the output. I need something that looks like this:

0: {Number: 1, newNumber:"1" }
1: {Number: 2, newNumber: "2" }

I tried using .push, but this just added it as a new object e.g.

0: {Number: 1, }
1: {Number: 2, } 
3: {newNumber: "1"}

I can't push into its corresponding object...


Solution

  • You can iterate over the data with Array.prototype.map and add the additinal key to the Object:

    var data = [{Number: 1 }, {Number: 2 }];
    
    var result = data.map(el => ({...el, newNumber: String(el.Number)}))
    
    console.log(result);