how to convert multidimention array to arr in object

  • A+
Category:Languages

can you explain the logic how to convert this 2d array to array and in array has objects, here is the input :

const arr = [ ["Tony", "a", "b"], ["Sara", "c", "z"]            ]; 

how to convert them to be:

obj = [ {  name:"Tony",   first:"a",   second:"b" }, {  name:"Sara",   first:"c",   second:"z" }    ] 

should we create 2 objects temporary and are ? to put them in the array, and how about looping? can we just use one-time looping? and how if that 2d array length is not same with ther 2d on the first or the second,
i do love to know the method, with explaning if you dont mind, and i do like you all dont use ES6 for this :), so i know the logic

 


Use Array.map(). In the map's callback, extract the values to variables, using array destructuring, than create the object with shorthand property names:

const arr = [["Tony", "a", "b"], ["Sara", "c", "z"]];  const result = arr.map(([name, first, second]) => ({   name,   first,   second }));  console.log(result);

And if you don't want to use Array.map(), you can build one using a for...of loop:

const map = (arr, cb) => {   const r = [];      for(const item of arr) {     r.push(cb(item));   }      return r; };  const arr = [["Tony", "a", "b"], ["Sara", "c", "z"]];  const result = map(arr, ([name, first, second]) => ({   name,   first,   second }));  console.log(result);

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: