简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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