Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make an array of specific field of object from array of objects

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)
    }
like image 864
S.Ang Avatar asked Nov 26 '25 13:11

S.Ang


2 Answers

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

like image 169
Eddie Avatar answered Nov 28 '25 02:11

Eddie


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);
like image 32
Ankit Agarwal Avatar answered Nov 28 '25 03:11

Ankit Agarwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!