Вы можете рассмотреть
{
"home1": {
"mesafe":11
}
}
в
{
"home1": {
"mesafe":11
},
// fakes
"home2": {},
"home3": {}...
}
Теперь значение для сортировки может быть описана в:
Получите все значение атрибута mesafe
из subObject и суммируйте их (если атрибут существует).
Для этого вы можете использовать _.reduce
.
var list = [
{ "home1": { "mesafe":11 } },
{ "home2": { "mesafe": 6 } },
{ "home3": { "mesafe":42 } },
{ "home4": { "mesafe":23 } },
{ "home5": { "mesafe": 5 } }
];
var sortedList = _.sortBy(list, function(item) {
// For each item, we acts as there not only have one attribute "homex", but there's many other like "homey : {}".
var res = _.reduce(item, function(res, sub) {
// So we can the again use reduce to iterate through them, and add the value if mesafe exist.
return (sub.mesafe == null) ? res : res + sub.mesafe;
}, 0);
return res;
});
console.log(sortedList);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
См метод [рода] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). – Vidul