javascript - 按作为字符串传递的 "grand.child.property"对对象数组进行排序的函数

标签 javascript arrays sorting

我看过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/

相关文章:

未找到 JavaScript 方法

javascript - 气体/Javascript : How do I set values to only empty rows at the bottom of the sheet

java - 这个选择排序代码有什么问题?

javascript - 从 JavaScript : Blob/createObjectURL vs. encodeURIComponent 中的字符串创建和下载文本文件

javascript - Django:创建一个 "changing button"或等待页面

python - 连接数组中的两个列表,用句点分隔

c - 自定义排序函数的奇怪结果

php - 使用 PHP 对不同字段的 mysql 输出进行排序

javascript - 是否可以使用Jquery操作表单的目标窗口

javascript - 使用 javascript position() 获取值