我看过all the solutions that only go 1 level deep ,但我想制定一个通用的解决方案,一个可以传递要比较的内部属性的函数,例如
var array = [
{grand: {child: {property: 2}}},
{grand: {child: {property: 1}}},
{grand: {child: {property: 3}}},
];
var sorted = array.sortBy('grand.child.property');
像这样,一般都会传递'dot.property.notation'
作为字符串。
但我想不出用 Array.sort
来做到这一点的方法的comparator function
.
Array.prototype.sortBy = function(predicate){
return this.sort(function(a, b){
// how to get a[.grand.child.property] from the
// parameter string 'grand.child.property'?
});
};
最佳答案
function getPropertyByPath(obj, path) {
return path.split('.').reduce(function (val, key) { return val[key]; }, obj);
}
array.sort(function (a, b) {
var property = 'grand.child.property';
return getPropertyByPath(a, property) - getPropertyByPath(b, property);
});
这可以/应该使我的一些内存技术更加有效,以避免重复调用 getPropertyByPath
,但我希望它说明了这个想法。
关于javascript - 按作为字符串传递的 "grand.child.property"对对象数组进行排序的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24476498/