59
[ {name:'hi',data:'1,2,3,4,5'} , {name:'hello',data:'5,4,3,2,1'} ]

What I need is to apply a split on data of each object in array so that the result would be:

[ {name:'hi',data:[1,2,3,4,5]} , {name:'hello',data:[5,4,3,2,1]} ]

I know I can loop through the array using for each and produce a new array, but is there a better, faster method?

var arr = [{
    name: 'hi',
    data: '1,2,3,4,5'
}, {
    name: 'hello',
    data: '5,4,3,2,1'
}];

var new_arr = [];
for (i in arr) {
    var temp = {};
    temp.name = arr[i].name;
    temp.data = arr[i].data.split(',');
    new_arr.push(temp);
}
alex
  • 6,818
  • 9
  • 52
  • 103
Zalaboza
  • 8,899
  • 16
  • 77
  • 142

2 Answers2

86

You could use Array.prototype.map:

var new_array = old_array.map(function(e) { 
  e.data = e.data.split(','); 
  return e;
});

As the comment said, this way changes the old_array. You could also return a new object in the callback function without changing the original array.

ashleedawg
  • 20,365
  • 9
  • 72
  • 105
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • 5
    Note this modifies the objects in `old_array`. – Oriol Apr 21 '15 at 15:51
  • @xdazz is right you can see for yourself [here](http://jsbin.com/dorogobose/2/edit) – JustGage Apr 21 '15 at 15:54
  • Apparently excluding the `return e;` still gives the same result. Also, if you're intentionally changing the `old_array`, then `var new array =` is also unneeded. Therefore, a shorter version is: `old_array.map(function(e){ e.data = e.data.split(',') });` – ashleedawg Sep 20 '21 at 01:50
26
var data = [{
    name: 'hi',
    data: '1,2,3,4,5'
}, {
    name: 'hello',
    data: '5,4,3,2,1'
}];

You can use the Array.prototype.map on data to construct a new Array, like this

var result = data.map(function (currentObject) {
    return {
        name: currentObject.name,
        data: currentObject.data.split(",").map(Number)
    };
});

Here, we split the currentObject.data based on , and then we call Number function on all the split strings, so that you will get the result object's data as numbers, as you wanted in the question.

Output

[{
    name: 'hi',
    data: [1, 2, 3, 4, 5]
}, {
    name: 'hello',
    data: [5, 4, 3, 2, 1]
}]

let data = [{
    name: 'hi',
    data: '1,2,3,4,5'
  }, {
    name: 'hello',
    data: '5,4,3,2,1'
  }],
  result = data.map(function(currentObject) {
    return {
      name: currentObject.name,
      data: currentObject.data.split(",").map(Number)
    };
  });
console.log(result);
OXiGEN
  • 2,041
  • 25
  • 19
thefourtheye
  • 233,700
  • 52
  • 457
  • 497