Reputation: 91
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!!!
Upvotes: 4
Views: 12307
Reputation: 23859
It is quite simple if you jus use Array#map
in combination with Array#reduce
.
let data = [
[
['firstName', 'Joe'],
['lastName', 'Blow'],
['age', 42],
['role', 'clerk']
],
[
['firstName', 'Mary'],
['lastName', 'Jenkins'],
['age', 36],
['role', 'manager']
]
];
let result = data.map(item => item.reduce((acc, [key, val]) => ({ ...acc, [key]: val }), {}));
console.log(result);
Upvotes: 1
Reputation: 27192
You can use Object.fromEnteries() ECMAScript 2019 (ES10)
var arr = [
[['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']],
[['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']]
];
const object = arr.map(item => Object.fromEntries(item));
console.log(object);
Upvotes: 0
Reputation: 4481
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).
Upvotes: 9
Reputation: 386560
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; }
Upvotes: 6
Reputation: 97130
Using Array.prototype.map()
and Array.prototype.reduce()
with some array destructuring:
const result = data.map(entry => entry.reduce((a, [k, v]) => (a[k] = v, a), {}));
Demo snippet:
const data = [[['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']],
[['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']]];
const result = data.map(entry => entry.reduce((a, [k, v]) => (a[k] = v, a), {}));
console.log(result);
Upvotes: 1
Reputation: 1521
You can use map
to iterate over the subarrays
in your main array and then use reduce
to convert their child arrays to object properties.
var arr = [[['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']], [['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']]];
var result = arr.map(function(subArr){
return subArr.reduce(function(acc, data){
acc[data[0]] = data[1];
return acc;
},{})
});
console.log(result);
Upvotes: 1
Reputation: 68393
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) );
Upvotes: 1