Jo Ko Jo Ko - 3 months ago 15
React JSX Question

ReactJS + javascript: How to parse array into a new array?

I have an array of the following:

var oldArray = [
{number: '12345', alphabet: 'abcde'},
{number: '54321', alphabet: 'abcde'},
{number: '67891', alphabet: 'abcde'},
{number: '19876', alphabet: 'abcde'},
]


And I would like to extract only the
number
from the
oldArray
and create a new array of them called
newNumberArray
with only the strings and not as objects, like so:

var newNumberArray = [
{'12345'},
{'54321'},
{'67891'},
{'19876'},
]


How can I go about doing so?

Answer

Note that {'12345'} is not a valid JavaScript object, as the value is missing its key.


Going forward, I'll be assuming you want to achieve a result like the following:

["12345", "54321", "67891", "19876"]

The Array.prototype.map() function is helpful here:

var oldArray = [
    {number: '12345', alphabet: 'abcde'},
    {number: '54321', alphabet: 'abcde'},
    {number: '67891', alphabet: 'abcde'},
    {number: '19876', alphabet: 'abcde'},
]
  
var newNumberArray = oldArray.map(function(item) {
  return item.number
})
  
console.log(newNumberArray) // ["12345", "54321", "67891", "19876"]