Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Any Recursive-approach solutions on solving array to object/s (within array) in plain JS (no libraries). Basically I would want to send the same function to itself. At this time I get overwritten the object with the last iteration. i get:

{firstName: "Sallito", lastName: "Jordan", age: 16, role: "server"}

while i should get:

[
    {firstName: 'Eren', lastName: 'Duran', age: 22, role: 'admin'},
    {firstName: 'Sallito', lastName: 'Jordan', age: 16, role: 'server'}
]

The original array is:

var array = [
    [
         ['firstName', 'Eren'], ['lastName', 'Duran'], ['age', 22], ['role', 'admin']
    ], 
    [
        ['firstName', 'Sallito'], ['lastName', 'Jordan'], ['age', 16], ['role', 'server']
    ]
];

my current so-far solution is:

function transformData(array) {
   var obj = {};
     for(var i = 0; i < array.length; i++){        
       for(var j = 0; j < array[i].length; j++){
          for(var k = 0; k < array[i][j].length; k++){
                 if(k === 0){
                 var currentKey = array[i][j][k];
                 var currentValue = array[i][j][k + 1];
                     obj[currentKey] = currentValue;
                 }
          }
      }
  }
     return obj;
  }

Please offer just recursive ideas since I know how to do it with forEach and map.reduce ways. I really want to learn recursive-ity. Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
144 views
Welcome To Ask or Share your Answers For Others

1 Answer

With pure JS you may do as follows;

var data = [ [ ['firstName', 'Eren'],
               ['lastName', 'Duran'],
               ['age', 22],
               ['role', 'admin'] ],
             [ ['firstName', 'Sallito'],
               ['lastName', 'Jordan'],
               ['age', 16],
               ['role', 'server'] ]
           ],
 objData = data.map(a => a.reduce((o,t) => Object.assign(o,{[t[0]]:t[1]}),{}));
console.log(objData);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...