将对象隐藏到组合/对象的数组

时间:2016-04-08 03:48:45

标签: javascript json underscore.js lodash

使用lodash或下划线。我正在尝试转换此对象:

{
  "variations": {
    "versions": ["sport", "generic"],
    "devices": ["mobile", "tablet"]
  }
}

到此:

var variations = [{
  "version": "sport",
  "device": "mobile"
}, {
  "version": "sport",
  "device": "tablet"
}, {
  "version": "generic",
  "device": "mobile"
}, {
  "version": "generic",
  "device": "tablet"
}];

这样做的最佳/最短方法是什么?

3 个答案:

答案 0 :(得分:0)

对lodash或不受欢迎的人不确定。但是通过简单的jquery,我已经做到了这一点。看看。

var object={
  "variations": {
    "versions": ["sport", "generic"],
    "devices": ["mobile", "tablet"]
  }
};
var variations=[];
$.each(object.variations.versions, function(i, j) { 
    $.each(object.variations.devices, function(k, l) { 
        variations.push({version:j,device:l});
    });
});

答案 1 :(得分:0)

我认为您想将object key设置为新variable name并执行内部对象值的组合。

<script type="text/javascript">
//here I created two object keys for more clear
var json ={
  "variations": {
    "versions": ["sport", "generic"],
    "devices": ["mobile", "tablet"]
  },
  "another_variations": {
    "versions": ["sport", "generic"],
    "devices": ["mobile", "tablet"]
  }
};

for(var i in json){     
     window[i] = []; //here window[variable] will make global variable
     ver = Object.keys(json[i])[0];//Object.keys(json[i]) get object keys ~["versions","devices"]
     dev = Object.keys(json[i])[1];
    window[i].push(
    {    
    [ver]:json[i].versions[0],
    [dev]:json[i].devices[0]
    },
    {
    [ver]:json[i].versions[0],
    [dev]:json[i].devices[1]
    },
    {
    [ver]:json[i].versions[1],
    [dev]:json[i].devices[0]
    },
    {
    [ver]:json[i].versions[1],
    [dev]:json[i].devices[1]
    });    
}
console.log(variations);        //here can call object key as a variable name if you 
console.log(another_variations);//don't use `window[variable]` in above, this will print undefined error
</script>

答案 2 :(得分:0)

使用https://gist.github.com/wassname/a882ac3981c8e18d2556

找到解决方案
_.mixin({
  cartesianProductOf: function(args) {
    if (arguments.length > 1) args = _.toArray(arguments);
    // strings to arrays of letters
    args = _.map(args, opt => typeof opt === 'string' ? _.toArray(opt) : opt)
    return _.reduce(args, function(a, b) {
      return _.flatten(_.map(a, function(x) {
        return _.map(b, function(y) {
          return _.concat(x, [y]);
        });
      }), true);
    }, [
      []
    ]);
  },
  cartesianProductObj: function(optObj) {
    var keys = _.keys(optObj);
    var opts = _.values(optObj);
    var combs = _.cartesianProductOf(opts);
    return _.map(combs, function(comb) {
      return _.zipObject(keys, comb);
    });
  }
});

见工作:

https://jsfiddle.net/rickysullivan/5ryf9jsa/