Oiproks
Oiproks

Reputation: 794

Copy single field of all objects in array in single array

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.

enter image description here

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:

Not bad.

Upvotes: 1

Views: 136

Answers (4)

Mamun
Mamun

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

ellipsis
ellipsis

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

Tushar Walzade
Tushar Walzade

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

Yosvel Quintero
Yosvel Quintero

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

Related Questions