If you want to do sort by that deep property age
, you can't use sortColumn
exactly as you have... Instead, one option is to modify it by making it an array of properties, like so:
sortColumn = { path:["other","age"], order:"asc" }
This way, you'd also have to modify the sort function - as seen in the example below:
const persons = [
{name:"alireza",family:"seif",other:{age:28,rate:30}},
{name:"fateme",family:"azizy",other:{age:27,rate:35}},
{name:"sara",family:"niki",other:{age:15,rate:15}}
]
const sortColumn = { path:["other","age"], order:"asc" }
persons.sort((person1, person2) =>
person1[sortColumn.path[0]][sortColumn.path[1]] > person2[sortColumn.path[0]][sortColumn.path[1]]
? sortColumn.order === "asc"
? 1
: -1
: person2[sortColumn.path[0]][sortColumn.path[1]] > person1[sortColumn.path[0]][sortColumn.path[1]]
? sortColumn.order === "asc"
? -1
: 1
: 0
);
console.log(persons)
However, this approach doesn't work to sort by "name"
since this sort function sorts your data by some piece of data that is two-layers deep (inside "other"
, then "age"
). Here's a modification you can make to the sort function which lets you sort by any properties, any number of layers deep into your data:
const persons = [
{name:"alireza",family:"seif",other:{age:28,rate:30}},
{name:"fateme",family:"azizy",other:{age:27,rate:35}},
{name:"sara",family:"niki",other:{age:15,rate:15}}
]
const sortColumn = { path:["name"], order:"asc" }
persons.sort((person1, person2) => {
// get array of paths
const sortPaths = sortColumn.path;
// get values to sort by
const val1 = sortPaths.reduce((acc, path) => {
if (acc[path]) return acc[path]
else alert(`can't find prop ${path} in person1`);
}, person1)
const val2 = sortPaths.reduce((acc, path) => {
if (acc[path]) return acc[path]
else alert(`can't find prop ${path} in person2`);
}, person2)
return val1 > val2
? sortColumn.order === "asc"
? 1
: -1
: val2 > val1
? sortColumn.order === "asc"
? -1
: 1
: 0
});
console.log(persons)
https://stackoverflow.com/questions/59792589/sort-object-in-object-by-javascript/59792918#
As you can see in this second snippet, you can now search by a shallow property "name"
by using path: ["name"]
, but if you want to sort by a deep value, just add both properties to the path array like this: path: ["other", "age"]
Hope this helps!