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
3 Answers
Reset to default 8You 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 dopush
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
版权声明:本文标题:javascript - Make an array of specific field of object from array of objects - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744090861a2532006.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论