admin管理员组文章数量:1202803
I have data-structure like this:
[
{
"name": "AAAA",
"children": [
{"name": "vvv", "id": 3},
{"name": "vvv22", "id": 4}
]
},
{
"name": "BBBB",
"children": [
{"name": "ggg", "id": 5},
{"name": "ggggv22", "id": 6}
]
},
]
And I want to find and return child with given ID. How to achieve this using Underscore.js?
My current realisation without using Underscore:
for (var i = 0; i < data.length; i++) {
var dataItem= data[i];
for (var j = 0; j < dataItem.children.length; j++) {
var child = dataItem.children[j];
if (child .id == id) {
return child;
}
}
}
I have data-structure like this:
[
{
"name": "AAAA",
"children": [
{"name": "vvv", "id": 3},
{"name": "vvv22", "id": 4}
]
},
{
"name": "BBBB",
"children": [
{"name": "ggg", "id": 5},
{"name": "ggggv22", "id": 6}
]
},
]
And I want to find and return child with given ID. How to achieve this using Underscore.js?
My current realisation without using Underscore:
for (var i = 0; i < data.length; i++) {
var dataItem= data[i];
for (var j = 0; j < dataItem.children.length; j++) {
var child = dataItem.children[j];
if (child .id == id) {
return child;
}
}
}
Share
Improve this question
asked Jul 15, 2014 at 11:15
WelcomeToWelcomeTo
20.6k56 gold badges174 silver badges289 bronze badges
2 Answers
Reset to default 21- Pluck the
children
keys from your top level objects - Flatten the resulting array
- Find the first object matching the condition, e.g having the correct id
- Chain these operations
which leads to
var res = _(data).chain().
pluck('children').
flatten().
findWhere({id: 3}).
value();
And a demo
var data = [
{
"name": "AAAA",
"children": [
{"name": "vvv", "id": 3},
{"name": "vvv22", "id": 4}
]
},
{
"name": "BBBB",
"children": [
{"name": "ggg", "id": 5},
{"name": "ggggv22", "id": 6}
]
}
];
var res = _(data).chain().
pluck('children').
flatten().
findWhere({id: 3}).
value();
console.log(res);
<script src="http://underscorejs.org/underscore-min.js"></script>
I got this function using underscore which will do your work.
var getChild = function(id,data){
var allChildren = _.flatten(_.pluck(data,'children'));
var childWithId = _.find(allChildren,function(child){return child.id == id});
return childWithId;
}
var child = getChild(5,data);
console.log(child);
本文标签: javascriptUnderscorejs Find and return element in nested arrayStack Overflow
版权声明:本文标题:javascript - Underscore.js Find and return element in nested array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738617100a2102974.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论