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

Covert object to array of combinations/objects

本文关键字:对象 数组 组合 隐藏      更新时间:2024-03-12

使用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"
}];

做这件事最好/最短的方法是什么?

不确定是否使用lodash或undercore。但通过简单的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});
    });
});

我认为您想将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>

找到了一个解决方案,使用: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/