Monday, May 20, 2024
47
rated 0 times [  54] [ 7]  / answers: 1 / hits: 9511  / 10 Years ago, tue, july 15, 2014, 12:00:00

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;
}
}
}

More From » underscore.js

 Answers
13

  1. Pluck the children keys from your top level objects

  2. Flatten the resulting array

  3. Find the first object matching the condition, e.g having the correct id

  4. 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>




[#43874] Monday, July 14, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cristinadomoniquel

Total Points: 320
Total Questions: 94
Total Answers: 94

Location: Moldova
Member since Sat, Aug 6, 2022
2 Years ago
cristinadomoniquel questions
Wed, Apr 7, 21, 00:00, 3 Years ago
Tue, Dec 1, 20, 00:00, 4 Years ago
Mon, Nov 23, 20, 00:00, 4 Years ago
Mon, Aug 17, 20, 00:00, 4 Years ago
;