javascript 如何映射多维数组(使用下划线)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22799937/
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
How to map a multidimensional array (using Underscore)?
提问by GloryOfThe80s
I have a large, multidimensional array of JSON objects that I want to map through (using Underscore). For example:
我有一个大型的多维 JSON 对象数组,我想通过这些对象进行映射(使用 Underscore)。例如:
var dummyData = [
[{title: 'a'},{title : 'b'}],
[{title: 'a'},{title : 'b'}],
[{title: 'a'},{title : 'b'}],
[{title: 'a'},{title : 'b'}]
];
For the function body of the _.map
, I want to run each JSON object through a Backbone Model constructor. So far, I've tried something like this to accomplish this:
对于 的函数体_.map
,我想通过 Backbone Model 构造函数运行每个 JSON 对象。到目前为止,我已经尝试过这样的事情来实现这一点:
_.map(dummyData, function() {
_.each(dummyData, function(el, i) {
// run each object through the constructor
}
})
I'm getting caught up on the _.each
, though - since dummyData
isn't actually the 'list' that I want to loop through.
不过,我正在关注_.each
,因为dummyData
实际上并不是我想要遍历的“列表”。
Or am I thinking about this wrong altogether?
还是我完全在考虑这个错误?
回答by thefourtheye
Iterate over the elements of dummyData
, with _.map
like this
迭代 的元素dummyData
,_.map
像这样
_.map(dummyData, function(currentDummyData) {
return _.map(currentDummyData, function(el, i) {
// run each object through the constructor
})
});
dummyData
is an Array of Arrays. When you use _.map
with that, it picks up each array in the array of arrays and passes to the function, which we accept with function(currentDummyData) {..}
.
dummyData
是一个数组数组。当你使用_.map
它时,它会选择数组数组中的每个数组并传递给我们接受的函数function(currentDummyData) {..}
。
Inside that function, we again _.map
that array, because it is still an array. So, we iterate that to get individual elements and pass them to the function function(el, i) {..}
, where new Backbone models are created.
在该函数内部,我们再次使用_.map
该数组,因为它仍然是一个数组。因此,我们迭代它以获取单个元素并将它们传递给函数function(el, i) {..}
,在那里创建新的 Backbone 模型。
Note:You have to return the result of _.map
, like in the answer. Because, _.map
expects the function called to return an object and all the returned objects will be gathered to create a new array.
注意:您必须返回 的结果_.map
,就像在答案中一样。因为,_.map
期望被调用的函数返回一个对象,所有返回的对象将被收集起来以创建一个新数组。
For example,
例如,
console.log(_.map(dummyData, function(currentDummyData) {
return _.map(currentDummyData, function(el, i) {
return {title: el.title + el.title};
})
}));
will produce
会产生
[ [ { title: 'aa' }, { title: 'bb' } ],
[ { title: 'aa' }, { title: 'bb' } ],
[ { title: 'aa' }, { title: 'bb' } ],
[ { title: 'aa' }, { title: 'bb' } ] ]