将对象转换为顺序数组格式 - javascript?

时间:2013-10-21 12:15:26

标签: javascript

我有以下对象结构

 var obj = {"0":"direct","1":"indirect","2":"dir","3":"indir"};

预期输出为:

result = [["direct","indirect"],["indirect","dir"],["dir","indir"]];

我尝试过:

    var result = [];
    var array = [];
    for(var key in obj){
          if(array.length <2) {
              array.push(obj[key]);
          }else{
              array =[];
              array.push(obj[key-1]);
           }

       if(array.length == 2){
            result.push(array);
       }
     }
   console.log(result);

我得到的输出如下:

result = [["direct", "indirect"], ["indirect", "indir"]]

1 个答案:

答案 0 :(得分:2)

如果它们都是至少包含一个字符的字符串,那么你可以这样做:

var obj = {"0":"direct","1":"indirect","2":"dir","3":"indir"};
var result = [];

for (var i = 1; obj[i]; i++) {
    result.push([obj[i-1], obj[i]]);
}

从索引1开始,并推送数组中的当前和前一项。只要值是真实的,它就会继续,所以如果有一个空字符串,它就会停止。

如果可能存在需要包含的假值,则应首先计算属性。

var obj = {"0":"direct","1":"indirect","2":"dir","3":"indir"};
var result = [];

var len = Object.keys(obj).length;

for (var i = 1; i < len; i++) {
    result.push([obj[i-1], obj[i]]);
}