简体   繁体   English

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

[英]Converting Object to sequential array format - javascript?

I am having following object structure 我有以下对象结构

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

Expected output is: 预期产出是:

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

What I have tried: 我尝试过的:

    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);

I am getting the output as follows: 我得到的输出如下:

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

If they're all strings that have at least one character, then you can do this: 如果它们都是至少包含一个字符的字符串,那么您可以这样做:

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]]);
}

It starts at index 1 and pushes the current and previous items in an Array. 它从索引1开始,并推送数组中的当前和前一项。 It continues as long as the values are truthy, so if there's an empty string, it'll stop. 只要值是真实的,它就会继续,所以如果有一个空字符串,它就会停止。

If there could be falsey values that need to be included, then you should count the properties first. 如果可能存在需要包含的假值,则应首先计算属性。

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]]);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM