Skip to content Skip to sidebar Skip to footer

Array Of Array To Object - Javascript

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 like array

Solution 1:

You can use Array.prototype.map and Array.prototype.reduce to get the desired result like this:

var list = [
  [
    ['itemCode', 1],
    ['item', 'Pen'],
    ['cashier', 'Sam']
  ],
  [
    ['itemCode', 2],
    ['item', 'Eraser'],
    ['cashier', 'Kim']
  ]
];

functionresult(arr) {
  return arr.map(function(sub) {
    return sub.reduce(function(acc, e) {
      acc[e[0]] = e[1];
      return acc;
    }, {});
  })
}

console.log(result(list));

Note: you can't relly on the order of the object poperties.

Solution 2:

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']
    ]
  ];


functionresult(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));

Solution 3:

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);functionresult(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));

Solution 4:

You can do it with a single line:

const newResult = list.map(a => a.map(([k,v]) => ({[k]: v})));

constshow = msg => {console.log(JSON.stringify(msg));};
const list = [
  [
    ['itemCode', 1],
    ['item', 'Pen'],
    ['cashier', 'Sam']
  ],
  [
    ['itemCode', 2],
    ['item', 'Eraser'],
    ['cashier', 'Kim']
  ]
];

const newResult = list.map(a => a.map(([k,v]) => ({[k]: v})));
show(newResult);

Solution 5:

Your question could possibly be addressed by using a relatively recent feature in JavaScript: map objects.

Note that when you have an array of indeterminate length where each element is itself an array that is two elements long, you can convert the outer array into a map object instead of just a plain object. e.g. const newMapObj = new Map([['a', 1], ['b', 2]]);. Entering that into a terminal and then checking console.log(newMapObj) produces the following: Map { 'a' => 1, 'b' => 2 }. In your example, you could do this with each of your two list elements/store items, i.e. you would end up with an array of 2 map objects.

Such map objects have some convenient features, such as get and has. Some people also find them frustrating because of e.g. a lack of some helpful methods used with, say, arrays, like, um, well, the map method. (Note that the map method on arrays and the map/Map data object type are two completely different things. I know, it's confusing.)

The code snippet below creates an array of such map objects, one for each outer array element (i.e. one for each store 'item'), with one simple line:

const newResult = list.map(a =>newMap(a));

Unfortunately, at this point in time at least, the code snippet tool here on Stack Exchange doesn't allow us to simply show the map object using console.log the way you can with, say, a plain object or an array. As a 2nd best substitute, the code snippet below logs out some of the results of using the map objects, just to demonstrate that the map objects were in fact created.

When I do the same thing in a Mac terminal (i.e. define list as the nested arrays in your question and then calculate newResult as above), console.log(newResult) shows the following:

[ Map { 'itemCode' => 1, 'item' => 'Pen', 'cashier' => 'Sam' },
  Map { 'itemCode' => 2, 'item' => 'Eraser', 'cashier' => 'Kim' } ]

In other words, it is an array of map objects instead of an array of objects.

If you're interested in this recent JavaScript feature, you should check out the MDN documentation on the Map data object.

Whether you really want to use map objects or plain objects depends on your use case. The MDN documentation linked above has a short section to help you determine whether you want to use map objects or plain objects.

const list = [
  [
    ['itemCode', 1],
    ['item', 'Pen'],
    ['cashier', 'Sam']
  ],
  [
    ['itemCode', 2],
    ['item', 'Eraser'],
    ['cashier', 'Kim']
  ]
];

const newResult = list.map(a =>newMap(a));
console.log('The name for the 1st item is:', newResult[0].get('item'));
console.log('The cashier for the 2nd item is:', newResult[1].get('cashier'));

Post a Comment for "Array Of Array To Object - Javascript"