admin管理员组文章数量:1327972
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 e 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.
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 e 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.
Share Improve this question edited Apr 3, 2019 at 16:41 Shidersz 17.2k2 gold badges27 silver badges51 bronze badges asked Apr 3, 2019 at 15:15 DamagedcaseDamagedcase 754 bronze badges 4-
I don't see any reason to do it another way if this way works well for you. If anything, your code right now is more readable than it would be using
.map()
or.forEach()
. Is there a reason why you would want to do it another way? – Cristian C. Commented Apr 3, 2019 at 15:20 - 2 Whenever you create an empty array, and iterate over something and add it to the array, you should probably use Array#map, but if your code works, it's not a good fit for this forum. Maybe codereview.stackexchange. Another suggestion, create a function that converts each line of you array into an object. – Ruan Mendes Commented Apr 3, 2019 at 15:20
- I just started learning programming and learned about methods related to arrays recently. I just wanted apply what I've learned, but it didn't work out too well after hours of trying. I will avoid this kind of question in the the future. Thank you for your ments! – Damagedcase Commented Apr 3, 2019 at 15:25
- There are enough answers here... I'd go with map reducer because you might have to reduce, also what happens if the array has the same key in separate indexes, reduce to me sounds correct – Jony-Y Commented Apr 3, 2019 at 15:28
7 Answers
Reset to default 5In 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; }
Using map and reduce.
var array = [
[['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']],
[
['firstName', 'Mary'],
['lastName', 'Jenkins'],
['age', 36],
['role', 'manager']
]
];
var transformed = array.map(a=> a.reduce((c, p) => {c[p[0]] = p[1]; return c;},{}));
console.log(transformed);
To achieve expected result, use below option of using map and forEach
var array = [
[['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']],
[
['firstName', 'Mary'],
['lastName', 'Jenkins'],
['age', 36],
['role', 'manager']
]
];
console.log(array.map(val => {
const result = {}
val.forEach(v => {
result[v[0]] = v[1]
})
return result
}))
codepen - https://codepen.io/nagasai/pen/ROWmEX
yes, you can do it in one line.
var array = [
[['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']],
[
['firstName', 'Mary'],
['lastName', 'Jenkins'],
['age', 36],
['role', 'manager']
]
];
const transformed = array.map(upperArr => upperArr.reduce((acc, itemArr) => { acc[itemArr[0]] = itemArr[1]; return acc;}, {}));
console.log(transformed);
You can use map
and reduce
in tandem (map each element to the result of the reduce function, which transforms each element into a key/value pair):
var array=[[['firstName','Joe'],['lastName','Blow'],['age',42],['role','clerk']],[['firstName','Mary'],['lastName','Jenkins'],['age',36],['role','manager']]];
const result = array.map(e =>
e.reduce((a, [k, v]) => ((a[k] = v) || 1) && a, {}))
;
console.log(result);
Your function with map and forEach:
function transformEmployeeData(array) {
return array.map(toObject => {
const obj = {};
toObject.forEach(([key, value]) => {
obj[key] = value;
});
return obj;
});
};
var array = [
[['firstName', 'Joe'], ['lastName', 'Blow'], ['age', 42], ['role', 'clerk']],
[
['firstName', 'Mary'],
['lastName', 'Jenkins'],
['age', 36],
['role', 'manager']
]
];
function transformEmployeeData(array) {
return array.map(toObject => {
const obj = {};
toObject.forEach(([key, value]) => {
obj[key] = value;
});
return obj;
});
};
console.log(transformEmployeeData(array));
版权声明:本文标题:javascript - Is there a way to solve this problem by using .forEach or .map instead of for-loop? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742252571a2441035.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论