admin管理员组文章数量:1394593
I have an array:
[
{
meta:'abc'
data:
{
name:'asd',
title: 'bbb'
}
},
{
meta:'abc'
data:
{
name:'asd',
title: 'bbb'
},
{
meta:'abc'
data:
{
name:'asd',
title: 'bbb'
}
}
]
I want to convert it to new array, which will be:
[
{
name:'asd',
title: 'bbb'
},
{
name:'asd',
title: 'bbb'
{
name:'asd',
title: 'bbb'
}
]
I want to take only the data elements, and to create from them a new array. How can I do it the fastest way? And how can I do it with lodash?
Thanks!
I have an array:
[
{
meta:'abc'
data:
{
name:'asd',
title: 'bbb'
}
},
{
meta:'abc'
data:
{
name:'asd',
title: 'bbb'
},
{
meta:'abc'
data:
{
name:'asd',
title: 'bbb'
}
}
]
I want to convert it to new array, which will be:
[
{
name:'asd',
title: 'bbb'
},
{
name:'asd',
title: 'bbb'
{
name:'asd',
title: 'bbb'
}
]
I want to take only the data elements, and to create from them a new array. How can I do it the fastest way? And how can I do it with lodash?
Thanks!
Share Improve this question edited Feb 3, 2016 at 15:40 user663031 asked Feb 3, 2016 at 15:34 user3712353user3712353 4,2194 gold badges22 silver badges35 bronze badges 4- Why do you care how fast it is? Are you programming on a Commodore 64? – user663031 Commented Feb 3, 2016 at 15:40
- I'd assume that the OP means "the cleanest way". – isherwood Commented Feb 3, 2016 at 15:40
-
Where are you stuck? Do you not know how to loop over an array and do something with each of its elements? Do you not know the equivalent lodash utility? Are you stuck writing the logic for what to do with each element, namely extracting its
data
property? By the way, you tagged this "JSON", but it has nothing to do with JSON, which a string-based format for exchanging information. – user663031 Commented Feb 3, 2016 at 15:44 - 1 I mean the cleanest way. Got an answer. – user3712353 Commented Feb 3, 2016 at 15:53
2 Answers
Reset to default 6You can use _.map
var array = [{
meta: 'abc',
data: {
name: 'asd',
title: 'bbb'
}
}, {
meta: 'abc',
data: {
name: 'asd',
title: 'bbb'
}
}, {
meta: 'abc',
data: {
name: 'asd',
title: 'bbb'
}
}];
console.log(_.map(array, 'data'));
<script src="https://cdnjs.cloudflare./ajax/libs/lodash.js/4.2.0/lodash.js"></script>
Just you need is the map() native javascript method to arrays:
//considere that 'someArray' is the same as your.
var newArray = someArray.map(function(item){
return {name: item.data.name, title: item.data.title};
});
本文标签: javascriptHow to create a new array from child object propertiesStack Overflow
版权声明:本文标题:javascript - How to create a new array from child object properties - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744096072a2590304.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论