我有一个函数,用于根据属性对JavaScript对象数组进行排序:
// arr is the array of objects, prop is the property to sort by
var sort = function (prop, arr) {
arr.sort(function (a, b) {
if (a[prop] < b[prop]) {
return -1;
} else if (a[prop] > b[prop]) {
return 1;
} else {
return 0;
}
});
};
它适用于这样的数组:
sort('property', [
{property:'1'},
{property:'3'},
{property:'2'},
{property:'4'},
]);
但我也想能够按嵌套属性排序,例如:
sort('nestedobj.property', [
{nestedobj:{property:'1'}},
{nestedobj:{property:'3'}},
{nestedobj:{property:'2'}},
{nestedobj:{property:'4'}}
]);
然而这种方式并不起作用,因为无法像object['nestedobj.property']
这样做,应该是object['nestedobj']['property']
。
你知道如何解决这个问题并使我的函数能够使用嵌套对象的属性吗?
提前致谢。