-1

我陷入字典对象操作中,请帮助我的字典对象包含这些值 var dict = [];

 [Object { key="BRTHDTC", value="1"},
  Object { key="BRTHDTC", value="2"},
  Object { key="BRTHDTC", value="3"},
  Object { key="BRTHDTC", value="1"}, 
  Object { key="ASIAN", value="1"}, 
  Object { key="ASIAN", value="2"}, 
  Object { key="ASIAN", value="3"}, 
  Object { key="ASIAN", value="1"}]

我想在下面的对象中转换这些值

 [Object { key="BRTHDTC", value="1,2,3"}, 
 Object { key="ASIAN", value="1,2,3"}]

我如何才能实现上述目标......

4

2 回答 2

0

可能的解决方案之一:

var shortArr  =  [];

var longArr = [
    { key : "BRTHDTC", value : "1"},
    { key : "BRTHDTC", value : "2"},
    { key : "BRTHDTC", value : "3"},
    { key : "BRTHDTC", value : "1"}, 
    { key : "ASIAN", value : "1"}, 
    { key : "ASIAN", value : "2"}, 
    { key : "ASIAN", value : "3"}, 
    { key : "ASIAN", value : "1"}
];

var key, value;
for (var i = 0; i < longArr.length; i++) {
    key = longArr[i].key;
    value = longArr[i].value;

    var j = 0;
    while (j < shortArr.length) {
        if (key == shortArr[j].key ) {
            if (shortArr[j].value.indexOf(value) == -1)
                shortArr[j].value = shortArr[j].value.concat(",", value);
            break;
        }
        j++;
    }

    if (j == shortArr.length) {
        shortArr.push({"key": key, "value": value});
    }
}
于 2013-11-07T09:24:22.827 回答
0
var dict = [];  
var tmpdict= [
     { key : "BRTHDTC", value : "1"},
     { key : "BRTHDTC", value : "2"},
     { key : "BRTHDTC", value : "3"},
     { key : "BRTHDTsC", value : "1"}, 
     { key : "ASIAN", value : "1"}, 
     { key : "ASIAN", value : "2"}, 
     { key : "ASIAN", value : "3"}, 
     { key : "ASIAN", value : "1"}
  ];  

 $.each(tmpdict, function(key, val) {                          
           if(findElement(dict ,val.key) == -1){
                dict.push({
                   key:  val.key,
                   value: val.value
                  }); 
               }
           else{
          if(dict[findElement(dict ,val.key)] ['value'].indexOf(val.value) < 0 )
              dict[findElement(dict ,val.key)]['value'] = dict[findElement(dict ,val.key)]['value'] + ',' + val.value ;
                  }                         
              });  



   function findElement(pdict ,element){
     var index = -1 ; 
      for(var i= 0 ;i<pdict.length ;i++){
       if(pdict[i]['key'] == element){
          index = i ;
           break;
        }
    }
 return index ;
}   
于 2013-11-07T11:08:26.317 回答