使用复选框创建键值对

时间:2019-07-05 17:13:01

标签: javascript vue.js

我得到了这种类型的数组对象:

{
  "Brand": [" AWG - ALL WEATHER GEAR", "addidas", "28", "blue", "cyan"],
  "fit": [" AWG - ALL WEATHER GEAR", "addidas", "28", "blue", "cyan"],
  "color": [" AWG - ALL WEATHER GEAR", "addidas", "28", "blue", "cyan"]
}

具有动态显示的复选框类别和此类别。 我想要这种类型的对象数组

"Brand": [" AWG - ALL WEATHER GEAR", "addidas"],
"fit": ["28", "30", "32"],
"color": ["blue", "cyan"]

这是vue.js中的复选框代码

<input type="checkbox" 
      class="form-check-input" 
      :id="attributefilter.id" 
      :value="filter.id+':'+attributefilter.id" 
      name="attribute_category" 
      v-model="attributeModel" 
      @change="filterbyId(filter.id,attributefilter.id)">

这是js

methods:{

    filterbyId: function (a,b) {

    if(this.fval.includes(b)){
     this.fval.splice(this.fval.indexOf(this.b), 1)
    } else {
      this.fval.push(b)
    }

    this.result[a] = this.fval;
    this.fstr = JSON.stringify(this.result);

}

1 个答案:

答案 0 :(得分:0)

               var farray=["brand:xx","brand:yy","fit:28","fit:34","color:red","color:blue"];

    var obj = farray.reduce(function(acc, cur, i) {
                    cur=cur.split(':');
                    var key=cur[0];
                    if (!acc.hasOwnProperty(key))
                    { 
                        acc[key]=[];
                        acc[key].push(cur[1]);
                    }else{
                        acc[key].push(cur[1]);
                    }

                    //console.log(acc)
                    //alert(fstr);
                    return acc;
                    }, {});

        fstrobj = JSON.stringify(obj);
        alert(fstrobj)