javascript - 使用下划线展开功能

标签 javascript underscore.js

我需要 mongodb 的 $unwind 类似带下划线的功能,这样

[{
    groups: [{ name: 'test 1' }, { name: 'test 2' }],
    id: 1
}]

成为了

[{
    id: 1,
    group: {
        name: 'test 1'
    }
}, {
    id: 1,
    group: {
        name: 'test 2'
    }
}]

可以用下划线来完成吗?

最佳答案

您可以为目标字段中的每个元素映射一个新对象。例如,使用 mixin 并假设您想要一个类似于 _.unwind(object, field) 的方法签名:

_.mixin({
    unwind: function(o, field) {
        return _.map(o[field], function(val) {
            var cloned = _.clone(o);
            cloned[field] = val;
            return cloned;
        });
    }
});

你可以像这样使用它:

_.unwind({
    groups: [{ name: 'test 1' }, { name: 'test 2' }],
    id: 1
}, 'groups');

function log(obj) {
  document.getElementById('logged').innerHTML+= '<p>'+JSON.stringify(obj)+'</p>';
}

_.mixin({
    unwind: function(o, field) {
        return _.map(o[field], function(val) {
            var cloned = _.clone(o);
            cloned[field] = val;
            return cloned;
        });
    }
});

var o = { _id : 1, item : "ABC1", sizes: [ "S", "M", "L"] };
log(_.unwind(o, 'sizes'));

var g = {
    groups: [{ name: 'test 1' }, { name: 'test 2' }],
    id: 1
};
log(_.unwind(g, 'groups'));
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>

<div id='logged'></div>

关于javascript - 使用下划线展开功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26037539/

相关文章:

javascript - 下划线 bindAll : preserving the 'this' context

javascript - 将一组回调函数减少为一个回调

javascript - 如何在用户单击元素时触发声音

javascript - underscore.js 如何合并 2 个集合

javascript - 如何使用下划线将行项目合并到组中?

javascript - 为什么 Array.some() 方法表现不同?

javascript - 如何提取/哪里具有数组属性的 javascript 列表

javascript - 使用 jQuery UI 可选择时如何获取所选项目的列表?

javascript - Y 轴系列在 Highcharts 中重复

javascript - 如何在nodejs中将项目添加到数组中