简体   繁体   English

在具有未索引数组键的数组中按键对Javascript对象进行排序

[英]Sort Javascript Object by key in an Array with non indexed array key

The problem I face is that my array is not indexed by 0,1,2,3 etc. Its indexes are an id 0654, 3423, 7543 etc... so for example: 我面临的问题是我的数组没有被0、1、2、3等索引。它的索引是id 0654、3423、7543等...因此,例如:

var obj = {};
obj["0654"] = { "Name" : "Tony" };
obj["3423"] = { "Name" : "Fred" };
obj["7543"] = { "Name" : "Dave" };

I am looking for a way to sort these by the Name key. 我正在寻找一种通过名称键对它们进行排序的方法。 But I keep getting an not a function error. 但是我一直收到一个不是函数错误。 Not too sure what I am doing wrong. 不太确定我在做什么错。 I am using this code to sort it: 我正在使用此代码对其进行排序:

Array.prototype.sortByProp = function(p){
    return this.sort(function(a,b){
        return (a[p].toLowerCase() > b[p].toLowerCase()) ? 1 : (a[p].toLowerCase() < b[p].toLowerCase()) ? -1 : 0;
    });
}

Doing this: 这样做:

obj.sortByProp("Name");

Any guidance or the best way to approach this would be greatly appreciated... If this is a duplicate from another post, my apologies please point me in the right direction because I searched for this scenario all over and could not find the solution? 任何指导或解决此问题的最佳方法将不胜感激...如果这是另一篇文章的重复文章,对不起,请向正确的方向指点我,因为我一直在寻找这种情况,而找不到解决方案? Also, if you could tell me why this doesn't work too I can then understand objects a little better. 另外,如果您能告诉我为什么它也不起作用,那么我可以更好地理解对象。

UnderscoreJS is your best friend! UnderscoreJS是您最好的朋友!

_.sortBy(obj, 'Name');

Try it yourself. 自己尝试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM