将函数应用于JavaScript数组中的每个对象 [英] Applying a function to each object in a JavaScript array

查看:74
本文介绍了将函数应用于JavaScript数组中的每个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我需要的是在 data 数组中的每个对象,结果如下:

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);
}


推荐答案

你可以使用 Array.prototype.map

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

正如评论所说,这样改变 old_array ,您可以在回调函数中返回一个新对象而不更改为原始数组。

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.

这篇关于将函数应用于JavaScript数组中的每个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆