0

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?

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
Jo Ko
  • 7,225
  • 15
  • 62
  • 120
  • 2
    This would be done quite easily with native JavaScript's [`Array.map()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map). – filoxo Aug 23 '16 at 19:31
  • 1
    Loop through the old array and push each `number` to a new array... – brso05 Aug 23 '16 at 19:31
  • 1
    React doesn't provide anything to help you with that. Use the native JavaScript API or a library like lodash. – Felix Kling Aug 23 '16 at 19:32

2 Answers2

3

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"]
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
1

That's a perfect job for .map ;)

var newNumberArray = oldArray.map(function(item){
    return item.number;
});

You can see it working here: https://jsfiddle.net/juanmirod/09yk7a3t/

More about map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Juanmi Rodriguez
  • 597
  • 5
  • 13