【发布时间】:2014-05-25 02:21:16
【问题描述】:
我正在尝试根据产品的颜色、尺寸和材料为其创建价格模式。 我目前的实现方式是维护 1 个包含所有选项的 JSON 对象,并尝试使用其选项的所有可能组合生成另一个 JSON 对象。 例如
var productOption = {
"color":["red","green","yellow"],
"size":["S","M","L"],
"material":["leather","linen"]
}
what I want to create something like follow
[
{
"red":{
"S":{
"leather":{
"cost":100,"available":true
}
}
}
},
{
"green":{
"S":{
"leather":{
"cost":100,"available":true
}
}
}
},
....
]
所以我可以做类似 price["red"]["S"]["leather"] 的操作来获取红色、皮革、小尺寸的价格。 有简单的方法吗?在Javascript或Python中。
编辑:
如果某些产品只有颜色和尺寸或只有颜色怎么办?
var productOption= { color :[...],size:[...]};
编辑 2:
我编写了以下代码来解决我的问题。如果您对如何改进我的代码有任何建议。请告诉我。
// I am using lodash for those underscore signs.
var processPrice = function(){
price = {};
var keys = _.keys(_.pick(priceOption,function(value,key){
return !_.isEmpty(value);
}));
if(keys.length>0){
genMatrix(keys,[],price);
}
};
var genMatrix = function(keys,options,obj){
var key = keys[0];
if(keys.length>1){
var subKeys = _.compact(keys);
subKeys.shift();
_.each(priceOption[key],function(opt){
var subOption = _.compact(options);
subOption.push(opt.value);
obj[opt.value]={};
genMatrix(subKeys,subOption,obj[opt.value]);
});
}else{
_.each(priceOption[key],function(opt){
obj[opt.value]={cost: 100, available: true};
});
}
};
【问题讨论】:
-
数据从何而来,即(例如)[red][S][leather] 的值从何而来?
-
@JayanthKoushik 如果您参考我们手动输入的成本和可用性信息。
标签: javascript python arrays list dictionary