0

I want to make an array of a specific field of object from an array of objects. Here is what I did. How it can be more efficient?

    var array_obectj = [
        {   a: 'somestring1',
            b: 42,
            c: false},
        {
            a: 'somestring2',
            b: 42,
            c: false
        }];

    var arrayP = [];

    for (var i in array_obectj){
        arrayP.push(array_obectj[i].a)
    }
S.Ang
  • 1
  • 2

3 Answers3

5

You can use map()

var array_obectj = [{
    a: 'somestring1',
    b: 42,
    c: false
  },
  {
    a: 'somestring2',
    b: 42,
    c: false
  }
];

var arrayP = array_obectj.map(o => o.a);

console.log(arrayP);

Doc: map()

Eddie
  • 26,593
  • 6
  • 36
  • 58
1

You can use object destructuring so that you can get the property value directly by specifying the property as {a}.

var array_obectj = [
  {   a: 'somestring1',
      b: 42,
      c: false},
  {
      a: 'somestring2',
      b: 42,
      c: false
  }];

var arrayP =  array_obectj.map(({a}) => a);
console.log(arrayP);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

How it can be more efficient?

First, we need to make it correct; for-in isn't how you loop through arrays. The equivalent would be a simple for loop:

for (var i = 0; i < array_object.length; ++i) {
    arrayP.push(array_obectj[i].a)
}

Then, what you have is already quite efficient. JavaScript engines optimize Array#push really well.

Other options:

  • Assign to the next index in the loop:

    for (var i = 0; i < array_object.length; ++i) {
        arrayP[i] = array_obectj[i].a;
    }
    

    Some JavaScript engines will optimize that better than push, but some do push better.

  • Use map:

    arrayP = array_object.map(e => e.a);
    

    ...but note that map has to make calls back to your callback function. Still, browsers optimize that well, too.


However, "how can it be more efficient" is usually not the question you want to ask. "How can it be clearer?" "How can I ensure the code is easy to read?" "How can I make this easily maintainable?" are all better questions to ask. Answering those, I'd say map is the clearest. It's a specific idiom for exactly this operation.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875