将函数应用于 JavaScript 数组中的每个对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29776996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Applying a function to each object in a JavaScript array
提问by Zalaboza
[ {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 dataof each object in array so that the result would be:
我需要的是对data数组中的每个对象应用拆分,以便结果是:
[ {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 eachand produce a new array, but is there a better, faster method?
我知道我可以使用循环遍历数组for each并生成一个新数组,但是有没有更好、更快的方法?
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);
}
回答by xdazz
You could use Array.prototype.map:
你可以使用Array.prototype.map:
var new_array = old_array.map(function(e) {
e.data = e.data.split(',');
return e;
});
As the comment said, this way change the old_array, you could return an new object in the callback function with no changing to the original array.
正如评论所说,通过这种方式更改old_array,您可以在回调函数中返回一个新对象,而无需更改原始数组。
回答by thefourtheye
var data = [{
name: 'hi',
data: '1,2,3,4,5'
}, {
name: 'hello',
data: '5,4,3,2,1'
}];
You can use the Array.prototype.mapon datato construct a new Array, like this
你可以使用Array.prototype.mapondata来构造一个新的数组,像这样
var result = data.map(function (currentObject) {
return {
name: currentObject.name,
data: currentObject.data.split(",").map(Number)
};
});
Here, we splitthe currentObject.databased on ,and then we call Numberfunction on all the split strings, so that you will get the result object's dataas numbers, as you wanted in the question.
在这里,我们split的currentObject.data基础上,,然后我们呼吁Number所有分割字符串的函数,这样你会得到的结果对象的data数字,因为你在这个问题想。
Output
输出
[{
name: 'hi',
data: [1, 2, 3, 4, 5]
}, {
name: 'hello',
data: [5, 4, 3, 2, 1]
}]

