Reputation: 794
I wanted to optimize my code removing a for-loop
.
groupFieldNames = [];
for (i = 0; i < data.length; i++) {
groupFieldNames.push(data[i].groupFieldName);
}
data
is an array of objects, each having 4 fields.
I am interested in the one identified as groupFieldName
.
Is there a way to avoid the loop and directly push the fields in the array?
EDIT:
I went with @Yosvel Quintero suggestion (to all the guys suggesting the map solution, he was the first one), and checked the performance. With a data array having ~60k objects I've got:
map
;for-loop
Not bad.
Upvotes: 1
Views: 136
Reputation: 68933
You can use Array.prototype.map()
with Destructuring assignment
in the following way:
const data = [
{id: 66, groupFieldName: 'test', other: 'other'},
{id: 66, groupFieldName: 'test2', other: 'other2'}
];
const groupFieldNames = data.map(({groupFieldName}) => groupFieldName);
console.log(groupFieldNames);
Upvotes: 1
Reputation: 12152
You can use map
var groupFieldNames = [];
var data=[{groupFieldName:'a'},{groupFieldName:'b'},{groupFieldName:'c'}]
console.log(data.map(x=>x.groupFieldName))
You can also use forEach
var groupFieldNames = [];
var data=[{groupFieldName:'a'},{groupFieldName:'b'},{groupFieldName:'c'}]
data.forEach(x=>groupFieldNames.push(x.groupFieldName))
console.log(groupFieldNames)
Upvotes: 1
Reputation: 3809
You could effectively use Array's built-in .map() here as follows -
var data = [
{ id: 1, groupFieldName: 'abcd' },
{ id: 2, groupFieldName: 'pars' }
];
var groupFieldNames = data.map(obj => obj.groupFieldName)
console.log(groupFieldNames);
Upvotes: 1
Reputation: 19070
You can use Array.prototype.map()
const groupFieldNames = [];
for (i = 0; i < data.length; i++) {
groupFieldNames.push(data[i].groupFieldName);
}
To:
const groupFieldNames = data.map(o => o.groupFieldName);
Upvotes: 2