如何排序嵌套的对象属性对象的JavaScript数组? [英] How to sort a JavaScript array of objects by nested object property?
本文介绍了如何排序嵌套的对象属性对象的JavaScript数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个功能进行排序基于属性对象的JavaScript数组:
I have this function to sort a JavaScript array of objects based on a property:
// 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;
}
});
};
它的工作原理像这样的数组:
It works with arrays like this:
sort('property', [
{property:'1'},
{property:'3'},
{property:'2'},
{property:'4'},
]);
但我希望能够还嵌套的属性进行排序,例如是这样的:
But I want to be able to sort also by nested properties, for example something like:
sort('nestedobj.property', [
{nestedobj:{property:'1'}},
{nestedobj:{property:'3'}},
{nestedobj:{property:'2'}},
{nestedobj:{property:'4'}}
]);
不过,这并不工作,因为它是不可能做这样的事情对象['nestedobj.property']
,它应该是对象['nestedobj'] ['财产']
。
你知道我怎么能解决这个问题,并与嵌套对象的属性我的函数的工作?
在此先感谢
推荐答案
您可以在拆分
和遍历数组更新道具
。 A
和 b
每次迭代中的下一个嵌套属性。
You can split the prop
on .
, and iterate over the Array updating the a
and b
with the next nested property during each iteration.
示例: http://jsfiddle.net/x8KD6/1/
var sort = function (prop, arr) {
prop = prop.split('.');
var len = prop.length;
arr.sort(function (a, b) {
var i = 0;
while( i < len ) { a = a[prop[i]]; b = b[prop[i]]; i++; }
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
});
return arr;
};
这篇关于如何排序嵌套的对象属性对象的JavaScript数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文