Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert nested Arrays to Object in javascript

I'm working on an assignment involving converting arrays to objects, and I'm a little tied up. We start with an array, containing two additional nested arrays, each of which contain a variable number of arrays (consisting of two values each).

The assignment is to convert all of this into one array, containing multiple objects. Within each object, there will be a series of key/value pairs equal to the two values from each of the smallest given arrays.

E.G.

The argument will look like this:

[
  [['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']],
  [['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']]
]

Given that input, the return value should look like this:

[{firstName: 'Joe', lastName: 'Blow', age: 42, role: 'clerk'}, {firstName: 'Mary', lastName: 'Jenkins', age: 36, role: 'manager'}]

Using debugger, I've determined that my code correctly assigns key/value pairs to the first object in the return statement. However, when the loop continues, instead of creating a new nested object, the key/value pairs from the first object are replaced, so I only end up with one object with the correct key value pairs from the final array that is evaluated.

Here's my code so far:

function transformEmployeeData(employeeData) {
  var obj = {}, arr = []
  for (var i = 0; i < employeeData.length; i ++) {
    for (var j = 0; j < employeeData[i].length; j ++) {
      var key = employeeData[i][j][0];
      var value = employeeData[i][j][1];
      obj[key] = value;
    }
    arr.push(obj);
  }
  return arr;
}

This one has my brain a little tied in knots...Any advice would be greatly appreciated!!!

like image 537
Alex Avatar asked Jan 11 '18 09:01

Alex


People also ask

Which method is used to convert nested arrays to object in JavaScript?

To convert an array to an object, use the reduce() method to iterate over the array, passing it an object as the initial value. On each iteration, assign a new key-value pair to the accumulated object and return the result. Copied! const arr = ['zero', 'one', 'two']; const obj4 = arr.

What is flat() in JavaScript?

flat() The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

What does it mean to flatten an array?

To flatten an array means to reduce the dimensionality of an array. In simpler terms, it means reducing a multidimensional array to a specific dimension. There are certain situations in which the elements of an array are an array, generally referred to as nested arrays.


3 Answers

An updated and one line solution to the question:

const input = [
  [['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']],
  [['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']]
]

const output = input.map(a => Object.fromEntries(a));

console.log(output);

Object.fromEntries() has been introduced in ECMAScript 2019 (ES10)

At the time of writing (April 11, 2019) this method has already been implemented by Chrome 73 and Firefox 63. Soon it will be implemented by the new versions of major browsers. The method is also available in BabelJs since version 7.4.0 (core-js@3).

like image 177
f-CJ Avatar answered Oct 20 '22 15:10

f-CJ


Beside the moving of the assignment of a new object inside of the first loop, you could consider to declare all variables at top of the function.

It's like an introduction of all actors in a drama.

function transformEmployeeData(employeeData) {
  var obj,
      arr = [],
      i, j,
      key, value;

  for (i = 0; i < employeeData.length; i ++) {
    obj = {}
    for (j = 0; j < employeeData[i].length; j ++) {
      key = employeeData[i][j][0];
      value = employeeData[i][j][1];
      obj[key] = value;
    }
    arr.push(obj);
  }
  return arr;
}

var array = [[['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']],[['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']]];

console.log(transformEmployeeData(array));
.as-console-wrapper { max-height: 100% !important; top: 0; }

For a short solution, you could use some ES5/ES6 features:

  • Array#map for retuning a new object for each element

  • Object.assign for assingning more properties to an object,

  • spread syntax ... which takes an array as arguments,

  • destructuring assignment, like a transfomer and

  • computed property names, some of the greates idea of Javascript at all. (I wish it would work for variables as well.)

function transformEmployeeData(array) {
    return array.map(person => Object.assign(...person.map(([k, v]) => ({ [k]: v }))));
}

var array = [[['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']],[['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']]];

console.log(transformEmployeeData(array));
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 31
Nina Scholz Avatar answered Oct 20 '22 14:10

Nina Scholz


Quite close, you just need to put the obj = {} inside the outer for-loop

function transformEmployeeData(employeeData) { 
   var arr = []
   for (var i = 0; i < employeeData.length; i ++) {
      var obj = {}; //observe this line
      for (var j = 0; j < employeeData[i].length; j ++) {
         var key = employeeData[i][j][0];
         var value = employeeData[i][j][1];
         obj[key] = value;
      }
      arr.push(obj);
   }
   return arr;
}

Demo

var arr = [
  [
    ['firstName', 'Joe'],
    ['lastName', 'Blow'],
    ['age', 42],
    ['role', 'clerk']
  ],
  [
    ['firstName', 'Mary'],
    ['lastName', 'Jenkins'],
    ['age', 36],
    ['role', 'manager']
  ]
];

function transformEmployeeData(employeeData) {
  var arr = []
  for (var i = 0; i < employeeData.length; i++) {
    var obj = {};
    for (var j = 0; j < employeeData[i].length; j++) {
      var key = employeeData[i][j][0];
      var value = employeeData[i][j][1];
      obj[key] = value;
    }
    arr.push(obj);
  }
  return arr;
}

console.log( transformEmployeeData(arr) );
like image 1
gurvinder372 Avatar answered Oct 20 '22 16:10

gurvinder372