js運算元組中資料排列組合

愛忽悠的唐唐發表於2018-08-06

需求: 將
var priceOption = {
age:[18,20],
sex:[‘男’,’女’],
hc:[‘2-6人’,’7-8人’]
}

上述物件中age與sex及hc自由組合:得到如下形式:
{age: 18, sex: “男”, hc: “2-6人”}
{age: 18, sex: “男”, hc: “7-8人”}
{age: 18, sex: “女”, hc: “2-6人”}
{age: 18, sex: “女”, hc: “7-8人”}
{age: 20, sex: “男”, hc: “2-6人”}
{age: 20, sex: “男”, hc: “7-8人”}
{age: 20, sex: “女”, hc: “2-6人”}
{age: 20, sex: “女”, hc: “7-8人”}

程式碼如下

// 需要引入lodash.
var priceFactor=['age','sex','hc']
var priceOption = {
    age:[18,20],
    sex:['男','女'],
    hc:['2-6人','7-8人']
}

function plzhFirst(datas){
       var array = [];
       var propObj = getFirstProp(datas);
       var propName= propObj.name;
       var propValue=propObj.value;
       if(_.isArray(propValue)){
          for(var i = 0 ;i<propValue.length;i++){
             var newObj = {};
             newObj[propName]=propValue[i];
             array.push(newObj);
          }
       }else{
          var newObj ={};
          newObj[propName]=propValue;
          array.push(newObj) 
       }
       for(var i=1;i<priceFactor.length;i++){
          array = plzh(array,priceOption[priceFactor[i]],priceFactor[i])
       }
       return array

 }

function getFirstProp(obj){
    var propObj = {}
    for(var i in obj){
        propObj.name=i;
        propObj.value=obj[i];
        return propObj;
     }
}


function plzh(arr1,arr2,nextAttr){
    var array = [];  
    for(var i=0;i<arr1.length;i++)  
     {  
            var obj = arr1[i];  
            for(var j=0;j<arr2.length;j++)  
            {  
                var newObj= _.cloneDeep(obj);
                var v2 = arr2[j]; 
                newObj[nextAttr]=v2;
                array.push(newObj);
            };  
      };  
     return array;  
}

var  endData =console.log(plzhFirst(priceOption));

/*根據表格資料合併成var priceOption = {
    age:[18,20],
    sex:['男','女'],
    hc:['2-6人','7-8人']
}形式*/
 function getSZ(){
    var defaultObj={}
    for(var i = 0 ;i<endData.length;i++){
         var defaultObj = combineObjectToOne(defaultObj,endData[i])
    }
     console.log(defaultObj);

 }
 getSZ();

function combineObjectToOne(object1,object2){
    var nextObj =_.cloneDeep(object1);  
    for(var i  in  object2){
        var oldValue = nextObj[i];
        var nextValue = object2[i];
         /*是陣列*/
      if(_.isArray(oldValue) && oldValue.indexOf(nextValue)==-1){
                oldValue.push(nextValue)
       }else if ((_.isString(oldValue)||_.isNumber(oldValue))&&oldValue!==nextValue){
                nextObj[i]=new Array(oldValue,nextValue)
      }else if(oldValue==null||oldValue==undefined){
                nextObj[i]=object2[i]
      }
    }
    return nextObj;
}


相關文章