Issue
I am trying to order an array of objects with the lodash orderBy function. When the iteratees contains a dot in the middle, the orderBy does not work any more.
Here is a plunker to explain the problem better. plunker
ar users = [
{ 'user': 'fred', 'age': 48 },
{ 'user': 'barney', 'age': 34 },
{ 'user': 'fred', 'age': 40 },
{ 'user': 'barney', 'age': 36 }
];
_.orderBy(users, ['user', 'age'], ['asc', 'desc']);
Any help will be appreciated.
Thank you in advance.
Solution
You could create a function for the access to exotic key names.
const
getPDot = o => o.value['p.'].val,
data = [{ id: 'b', value: { 'p.': { val: 2 } } }, { id: 'a', value: { 'p.': { val: 1 } } }, { id: 'c', value: { 'p.': { val: 3 } } }];
console.log(_.orderBy(data, [getPDot], ['asc']));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
A dynamic approach with a closure over key
.
const
getValue = key => o => o.value[key].val,
data = [{ id: 'b', value: { 'p.': { val: 2 } } }, { id: 'a', value: { 'p.': { val: 1 } } }, { id: 'c', value: { 'p.': { val: 3 } } }];
console.log(_.orderBy(data, [getValue('p.')], ['asc']));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
ES5
const
getValue = function (key) {
return function (o) {
return o.value[key].val;
};
}
data = [{ id: 'b', value: { 'p.': { val: 2 } } }, { id: 'a', value: { 'p.': { val: 1 } } }, { id: 'c', value: { 'p.': { val: 3 } } }];
console.log(_.orderBy(data, [getValue('p.')], ['asc']));
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
Answered By - Nina Scholz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.