7

Been stuck on this for a while.

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

To yield:

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

How do transform this exactly? I have tried triple nested for loops, map/reduce, and shift(), but I can't get it work transform exactly

6 Answers 6

5

Try this solution. Use Array#map to iterate over first level items. In the map function iterate over nested array items via Array#forEach and populate your object. Then from map return that object.

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

const newEmp = employees.map(emp => {
   const obj = {};
   
   emp.forEach(([prop, value]) => obj[prop] = value);
   
   return obj;
});

console.log(newEmp);

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

2 Comments

Wow I never thought to use [0] or [1], as it said the properties could be unpredictable. Thanks so much
You could also change the forEach function to ([key, value]) => obj[key] = value.
4

You can use Array#map to loop over the outside/main array.

Then you can use Array#reduce to change every array inside the main array to object.

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

employees = employees.map(employee => employee.reduce((acc, item) => {
    acc[item[0]] = item[1];
    return acc;
}, {}));

console.log(employees);

6 Comments

You could also change your inner function to (acc, [key, value]) => { acc[key] = value; return acc; }.
When I work with this, the first index returns as 'firstName', 'Joe' although the others return as lastName: 'Blow'
@AaditMShah Thanks for your note.
@jhazelton1 it works good for me. Also Did you try it in StackOverflow ? by clicking Run code snippet button.
@MohamedAbbas When I ran the code snippet, it worked in StackOverflow, so there must of been an error in my Atom text editor. Thanks
|
3

This is what I would do:

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

const entriesToObject = entries => {
    const object = {};
    for (const [key, value] of entries)
        object[key] = value;
    return object;
};

const result = employees.map(entriesToObject);

console.log(result);

Note that result can be converted back into employees by using Object.entries like so:

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

const employees = result.map(Object.entries);

console.log(employees);

Hence, the entriesToObject function is quite useful as it's the inverse function of Object.entries.

Comments

2

This seems to work:

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

translated = []

for(let dataGroup of employees) {
    person = {};

    for(let dataPoint of dataGroup) {
        person[dataPoint[0]] = dataPoint[1]
    }

    translated.push(person);
}

console.log(translated);

1 Comment

You could also change your inner for loop to for (const [key, value] of dataGroup) person[key] = value;.
2

You could use a combination of

  1. Array#map, for the complete new objects and the objects with just a key/value pair,

  2. Object.assign, for creating a new object out of single/value pair objects as parameters,

  3. spread syntax ..., for taking each element of an array as parameter,

  4. destructuring assignment, for getting the key and value out of an array and

  5. computed property names, for getting a dynamic key into an object literal.

employees.map(a => Object.assign(...a.map(([k, v]) => ({ [k]: v }))))
//        ^^^                         ^^^                              1 Array#map
//                 ^^^^^^^^^^^^^                                       2 Object.assign
//                               ^^^                                   3 spread syntax
//                                         ^^^^^^                      4 destructuring
//                                                       ^^^           5 computed prop

let employees = [[['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']], [['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']]];
    result = employees.map(a => Object.assign(...a.map(([k, v]) => ({ [k]: v }))));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

1 Comment

Using Object.assign along with the spread operator is really smart.
0

For Different Approach do with Array#reduce and Array#forEach function

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

var res = employees.reduce((a, b) => {
  var obj = {};
  b.forEach(function(i) {
    obj[i[0]] = i[1];
  })
  a.push(obj);
  return a;
}, [])

console.log(res)

6 Comments

Why don't you simply use map?
Already many people post with map function.That why I was adding a different approach .And what wrong with my answer.Why downvote to my answer? @AaditMShah
Using reduce over map unnecessarily complicates this problem. That being said, if you edit your answer and acknowledge that it's better to use map in this case then I'm willing to remove the downvote. I can't remove the downvote if you don't edit the answer.
complicated answers also one of the answer.It's a learning platform people are getting all type of things And surely I won't edit my answer.i'm not begging for vote
Sure, that's your prerogative. However, do note that I couldn't remove the downvote even if I wanted to because my vote is locked in. The only way I can remove it is if you edit your answer.
|

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.