使用下划线展开功能

时间:2014-09-25 11:31:39

标签: 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'
    }
}]

这可以用下划线完成吗?

7 个答案:

答案 0 :(得分:4)

您可以为目标字段中的每个元素映射新对象。例如,使用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>

答案 1 :(得分:1)

如果您需要展开一系列对象(更像是mongodb&#39; s展开),您可以使用此功能:

function unwindBy(arr, field){
  return _.transform(arr, function(r, o){ 
    Array.prototype.push.apply(r, 
      _.map(o[field], function(v){ return _.set(_.clone(o), field, v); })
    );
  }, []);
}

ES6允许将其重写得更短,并且不依赖于第三方库:

function unwindBy(arr, f) {
  return arr.reduce((r, o) => r.concat(o[f].map(v => ({ ...o, [f]: v }))), []);
}

示例:

unwindBy([{a:1, b:[1,2,3]}, {a:2, b:[3,4,5]}], 'b');
//[{a:1, b:1}, {a:1, b:2}, {a:1, b:3}, {a:2, b:3}, {a:2, b:4}, {a:2, b:5}]

答案 2 :(得分:0)

如果您要添加目标字段,可以使用以下代码段执行此操作。这是基于@ nikoshr的回答的修改。

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

_.mixin({
    unwind: function(o, field, toField) {
        if(!toField) toField = field;
        return _.map(o[field], function(val) {
            var cloned = _.clone(o);
            cloned[toField] = 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', 'group'));
&#13;
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>

<div id='logged'></div>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

  

此函数将有助于展开json对象。

function flatten()
{
    var objectData = [];
    var arrayData = [];
    var arrayDataKey = [];
    var resultSet = [];

    this.progress = function(doc){
        objectData = [this.getObjectData(doc)];
        this.unwindData(objectData,arrayData);
        return resultSet;
    }

    this.getObjectData = function(doc,keyId){ 
        var result = {};
        var index = '';
        if(keyId=='' || keyId==undefined){
            keyId = '';
        }

        for(key in doc){
            if(keyId==''){
                index = key;
            }else{    
                index =  keyId+'.'+key;
            }

            if(Array.isArray(doc[key])===true){
                if(typeof doc[key][0]=="object"){
                    arrayDataKey.push(key);
                    arrayData.push(doc[key]);
                }else{
                    result[index] = doc[key];
                }
            }else if(typeof doc[key]=="object"){
                if(doc[key]=="[object Object]"){
                    for (var k in data = this.getObjectData(doc[key],index)) { result[k] = data[k]; }
                }else{

                    result[index] = doc[key];
                }
            }else{
                result[index] = doc[key];
            }
        }
        return result;
    }

    this.unwindData = function(doc,objectData){
        for (var i = objectData.length - 1; i >= 0; i--) {
            resultSet = [];
            for(var key in doc){
                for (var prop in objectData[i]) {
                    objectData[i][prop] = this.getObjectData(objectData[i][prop]);
                    for(var k in objectData[i][prop]){
                        var ke = arrayDataKey[i]+'.'+k;
                        doc[key][ke] = objectData[i][prop][k];
                    }
                    resultSet.push(doc[key]);
                }
            }
            doc  = resultSet;
        }
    }
}

var flat = new flatten(); flat.progress();

答案 4 :(得分:0)

您可以签出lodash-unwind

样品用量:

const _ = require('lodash')
require('lodash-unwind')({ injected: true })
const data = [
{
    a: [ 1, 2 ],
    id: 'a1'
},
{
    a: [ 3, 4 ],
    id: 'a2'
}]
// Use unwind as part of lodash
const output = _.unwind(data, 'a')
// [
//   {
//     a: 1,
//     id: 'a1'
//   },
//   {
//     a: 2,
//     id: 'a1'
//   },
//   {
//     a: 3,
//     id: 'a2'
//   },
//   {
//     a: 4,
//     id: 'a2'
//   }
// ]

答案 5 :(得分:0)

您可以尝试使用npm软件包unwind-array来查看example usages

答案 6 :(得分:0)

您可以尝试使用npm软件包unwind-array

const { unwind } = require('unwind-array')
const result = unwind(
  {
    title: 'foobar',
    topLevelArr: [1, 2]
  },
  { path: 'topLevelArr' }
)
expect(result.length).to.be.equal(2)
expect(result).to.be.deep.equal([
  {
    title: 'foobar',
    topLevelArr: 1
  },
  {
    title: 'foobar',
    topLevelArr: 2
  }
])