Applying a function to each object in a JavaScript array
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);
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.