Glo*_*80s 7 javascript arrays dictionary underscore.js
我有一个大型的,多维的JSON对象数组,我想通过它来映射(使用Underscore).例如:
var dummyData = [
[{title: 'a'},{title : 'b'}],
[{title: 'a'},{title : 'b'}],
[{title: 'a'},{title : 'b'}],
[{title: 'a'},{title : 'b'}]
];
Run Code Online (Sandbox Code Playgroud)
对于函数体_.map,我想通过Backbone Model构造函数运行每个JSON对象.到目前为止,我已经尝试过这样的事情来实现这个目标:
_.map(dummyData, function() {
_.each(dummyData, function(el, i) {
// run each object through the constructor
}
})
Run Code Online (Sandbox Code Playgroud)
不过我已经陷入了困境_.each- 因为dummyData实际上并不是我想要循环的'列表'.
或者我是否完全在想这个错误?
the*_*eye 11
dummyData用_.map这样的方法迭代元素
_.map(dummyData, function(currentDummyData) {
return _.map(currentDummyData, function(el, i) {
// run each object through the constructor
})
});
Run Code Online (Sandbox Code Playgroud)
dummyData是一个数组数组.当你使用_.map它时,它会获取数组数组中的每个数组并传递给我们接受的函数function(currentDummyData) {..}.
在那个函数里面,我们再次_.map那个数组,因为它仍然是一个数组.因此,我们迭代它以获取单个元素并将它们传递给函数function(el, i) {..},在该函数中创建新的Backbone模型.
注意:您必须返回结果_.map,如答案中所示.因为,_.map期望调用的函数返回一个对象,并且将收集所有返回的对象以创建一个新数组.
例如,
console.log(_.map(dummyData, function(currentDummyData) {
return _.map(currentDummyData, function(el, i) {
return {title: el.title + el.title};
})
}));
Run Code Online (Sandbox Code Playgroud)
会产生
[ [ { title: 'aa' }, { title: 'bb' } ],
[ { title: 'aa' }, { title: 'bb' } ],
[ { title: 'aa' }, { title: 'bb' } ],
[ { title: 'aa' }, { title: 'bb' } ] ]
Run Code Online (Sandbox Code Playgroud)