Array of array to object - javascript

前端 未结 6 1440
不知归路
不知归路 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:51

    There are two problems.

    First, you're never adding the objects to the array or returning the array, you're just returning the object.

    Second, you're using the same object each time through the loop, just replacing its properties. You need to create a new object each time, and then add it to the array.

    It's also not a good idea to use for-in to iterate an array, use a numeric for loop (or the Array.prototype.forEach() function). See Why is using "for...in" with array iteration a bad idea?

    var list = [
        [
          ['itemCode', 1],
          ['item', 'Pen'],
          ['cashier', 'Sam']
        ],
        [
          ['itemCode', 2],
          ['item', 'Eraser'],
          ['cashier', 'Kim']
        ]
      ]
      //console.log(people.length);
    
    function result(array) {
      var newArr = [];
      for (var x = 0; x < array.length; x++) {
        var newObj = {};
        var item = array[x];
        for (var y = 0; y < item.length; y++) {
          var itemSingle = item[y];
          for (var i = 0; i < itemSingle.length; i+=2) {
            newObj[itemSingle[i]] = itemSingle[i + 1];
          }
        }
        newArr.push(newObj);
      }
      return newArr;
    }
    console.log(result(list));

提交回复
热议问题