0

我有以下对象结构

 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"]]
4

1 回答 1

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]]);
}
于 2013-10-21T12:24:17.857 回答