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)
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With