admin 管理员组

文章数量: 1086019

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)
    }

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)
    }
Share Improve this question asked Jun 15, 2018 at 8:17 S.AngS.Ang 311 silver badge3 bronze badges 1
  • const arrayP = array_obectj.map(({ a }) => a); Also try to use proper spelling in programming – CertainPerformance Commented Jun 15, 2018 at 8:17
Add a ment  | 

3 Answers 3

Reset to default 8

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()

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);

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.

本文标签: javascriptMake an array of specific field of object from array of objectsStack Overflow