I need to write a function that converts array elements within an array into objects. Although I've figured out a way to solve the problem by using for-loop
, I'm just wondering if there's more concise way to write up the solution by using methods such as forEach
or map
.
The problem is...
var array: [
[
['firstName', 'Joe'],
['lastName', 'Blow'],
['age', 42],
['role', 'clerk']
],
[
['firstName', 'Mary'],
['lastName', 'Jenkins'],
['age', 36],
['role', 'manager']
]
];
I need to convert the above array into something like this.
[
{ firstName: 'Joe', lastName: 'Blow', age: 42, role: 'clerk' },
{ firstName: 'Mary', lastName: 'Jenkins', age: 36, role: 'manager' }
];
The following is the code I've come up with by using a for-loop
.
function transformEmployeeData(array)
{
var output = [];
for (var i = 0; i < array.length; i++)
{
var obj = {};
for (var j = 0; j < array[i].length; j++)
{
obj[array[i][j][0]] = array[i][j][1];
}
output.push(obj);
}
return output;
}
Like I have mentioned above, it will be great if there's another way to solve the problem.
In some near future maybe you could use Object.fromEntries(). It is supported on some browsers version right now: Browser Compatibility:
var arr = [
[
['firstName', 'Joe'],
['lastName', 'Blow'],
['age', 42],
['role', 'clerk']
],
[
['firstName', 'Mary'],
['lastName', 'Jenkins'],
['age', 36],
['role', 'manager']
]
];
console.log(arr.map(Object.fromEntries));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}
You could map new objects by mapping the properties and join all properties to a single objects.
var data = [[['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']], [['firstName', 'Mary'], ['lastName', 'Jenkins'], ['age', 36], ['role', 'manager']]],
result = data.map(a => Object.assign(...a.map(([key, value]) => ({ [key]: value }))));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With