【发布时间】:2020-09-02 06:20:46
【问题描述】:
var customers = [
{'Name' : 'John', 'Attributes' : {'Age' : 5, 'Height' : 1.5, 'Country': 'USA', 'Clothes' : {'Shirts' : 5, 'Pants' : 8}}},
{'Name' : 'Andrew', 'Attributes' : {'Age' : 9, 'Height' : 1.8, 'Country': 'Canada', 'Clothes' : {'Shirts' : 2, 'Pants' : 5}}},
{'Name' : 'Lucifer', 'Attributes' : {'Age' : 11, 'Height' : 1.3, 'Country': 'France', 'Clothes' : {'Shirts' : 9, 'Pants' : 4}}}
];
function sort(valuePath, array){
let path = valuePath.split('.')
return array.sort((a, b) => {
return getValue(b,path) - getValue(a,path)
});
function getValue(obj, path){
path.forEach(path => obj = obj[path])
return obj;
}
}
如果我触发,我有这个功能的工作结构:
sort('Attributes.Height', customers)
但如果我选择使用文本,它就不起作用,例如:
sort('Attributes.Country', customers)
如何应用必要的修改?感谢您的宝贵时间。
【问题讨论】:
标签: javascript jquery arrays object multidimensional-array