最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Make an array of specific field of object from array of objects - Stack Overflow

programmeradmin6浏览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)
    }

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.

发布评论

评论列表(0)

  1. 暂无评论