3

This particular challenge calls for me to convert an array of arrays (is there a term for this?) into an array of objects, like so:

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

into:

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

Here's my code, so far:

function transformEmployeeData(array) {
var object={};
for (var i = 0; i < array.length;i++){
    var newArray = array[i];
    object[i] = newArray[1];
    object[newArray[0]] = object[i];
    newArray.push(object);
    delete object[i];
    }
return object;
}

var myArray= [['firstName','Joe'],['lastName','Blow'],['age', 42], ['role','clerk']];
transformEmployeeData(myArray); 

It seems to work great, until I add another nested array with a second (or third, or fourth, which is the whole point of the thing) employee's data.

I'm sure it has something to do with the loop, but I can't spot it.

Help appreciated!

1
  • Create a nested loop that iterates over newArray and sets the values from the even indexes to the props from the odd indexes. Btw, object[i] = newArray[1] - this line is redundant. Commented Mar 27, 2017 at 2:04

4 Answers 4

4

You need to create a new object inside the loop, so that you're creating a new object each time rather than just reassigning properties of the same object - you were pushing the same object into the array multiple times. (I'm not sure why you were using delete - you don't need it.)

So something like this:

function transformEmployeeData(data) {
  var result = []                              // new array to hold transformed data
  var key, value
  for (var i = 0; i < data.length; i++) {      // loop over employees
    var employee = {}                          // new object for current employee
    for (var j = 0; j < data[i].length; j++) { // loop over current employee details
      key = data[i][j][0]                      // extract property key name
      value = data[i][j][1]                    // and value
      employee[key] = value                    // add property to object
    }
    result.push(employee)                      // add new object to array
  }
  return result
}

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

console.log( transformEmployeeData(input) )

Or if you want to use some array functions like .map() and .reduce() you can "simplify" the code:

function transformEmployeeData(data) {
  return data.map(function(employee) {
    return employee.reduce(function(a, c) {
      a[c[0]] = c[1]
      return a
    }, {})
  })
}

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

console.log( transformEmployeeData(input) )

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, your answer was by far the most helpful.
3

Here's a solution using Array.prototype.map() and Array.prototype.reduce():

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

let arrayOfObjects = arrayOfArrays.map(array => array.reduce((acc, val) => {
  acc[val[0]] = val[1];
  return acc;
}, {}));

console.log(arrayOfObjects);

11 Comments

OP cannot deal with nested loops, and the community comes with a map/reduce solution. Does one seriously think OP would be able to learn from it?
@zerkms We can only hope so; that's why providing documentation links is good.
@zerkms As a member of the community, I provide answers for the community, not just for the OP.
@RobbyCornelissen s/provide answers/write code for free/. Code-only answers are rarely useful.
@zerkms It's not a code only answer. I provide links to the relevant pages in (what I assume is considered to be) the canonical documentation for all things JavaScript. Do you want me to reproduce that documentation here? As it stands, for a question titled "Array of Arrays to Array of Objects JS", I think my post answers the question, and is both correct and idiomatic JavaScript. If you think this is not the case, or if you think my answer violates any of SO's terms, feel free to flag or vote to delete.
|
1

Here's my solution using forEach Array object method

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

    transformEmployeeData(array);

    function transformEmployeeData(array){
      var employees = [];
      array.forEach(function(employee,index){
        var employeeObj = {};
        employee.forEach(function(data,key){
          employeeObj[data[0]] = data[1];
        });
        employees.push(employeeObj);
      });
      return employees;
    }

Comments

0

With Object.fromEntries, a one liner

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

console.log(input.map(elem => Object.fromEntries(elem)))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.