Array of array to object - javascript

前端 未结 6 1446
不知归路
不知归路 2020-12-21 11:02

I am looping to convert the array of array to object, but the final object has only the last item in the object. I am getting confused because you cant push in an object lik

6条回答
  •  悲哀的现实
    2020-12-21 11:55

    You have to use one loop to iterate over main array and then run loops to iterate over each array item (which also is an array) to construct object with properties you need. You can use map as main loop to return new array with items constructed inside each iteration. To construct those items you can use forEach:

    var list = [
        [
          ['itemCode', 1],
          ['item', 'Pen'],
          ['cashier', 'Sam']
        ],
        [
          ['itemCode', 2],
          ['item', 'Eraser'],
          ['cashier', 'Kim']
        ]
      ];
    
    
    function result(array) {
       let newArray = array.map(function(nestedArray) {
         let obj = {};
         nestedArray.forEach(function(item) {
           obj[item[0]] = item[1];
         });
         return obj;
         
       });
      return newArray;
    }
    console.log(result(list));

提交回复
热议问题