[英]Sort object keys with a sorted array
I have the below code that sorts object in an alphabetic order, I want to get away from having an alphabetic order and sort on my own chosen order. 我有以下代码按字母顺序对对象进行排序,我希望摆脱字母顺序并按自己选择的顺序进行排序。
var obj = { c: "see", a: "ay", b: "bee", d: "dee" }; console.log("Object order:"); var key, keys = []; for (key in obj) { keys.push(key); } console.log(keys.map(function(key) { return key + ": " + obj[key];}).join(", ")); console.log("Sorted order:"); keys = Object.keys(obj).sort() console.log(keys.map(function(key) { return key + ": " + obj[key];}).join(", "));
The above will output the object order of a, b, c, d - but lets say I want an array to have my own order eg 上面将输出a,b,c,d的对象顺序-但可以说我希望数组具有自己的顺序,例如
var sortedArray = ['b','c','d','a'];
So how do I know implement this sortedArray
into my .sort
? 那么我怎么知道在我的
.sort
实现这个sortedArray
呢?
Expected outcome: 预期结果:
var newObj = {
b: "bee",
c: "cee",
d: "dee",
a: "ay"
};
Thanks 谢谢
You can pass your custom sort function into the sort()
API. 您可以将自定义排序函数传递给
sort()
API。 See the example below: 请参阅以下示例:
var items = [ { name: 'Edward', value: 21 }, { name: 'Sharpe', value: 37 }, { name: 'And', value: 45 }, { name: 'The', value: -12 }, { name: 'Magnetic', value: 13 }, { name: 'Zeros', value: 37 } ]; // sort by value items.sort(function (a, b) { return a.value - b.value; }); // sort by name items.sort(function(a, b) { var nameA = a.name.toUpperCase(); // ignore upper and lowercase var nameB = b.name.toUpperCase(); // ignore upper and lowercase if (nameA < nameB) { return -1; } if (nameA > nameB) { return 1; } // names must be equal return 0; }); console.log(items)
It's a very weird pattern to a sort, but as you want, I made a function called CustomOrderBy
which will do a sort based on an array of keys. 这是一种非常奇怪的模式,但是根据需要,我创建了一个名为
CustomOrderBy
的函数,该函数将基于键数组进行排序。
Something like this: 像这样:
You have an array with the keys you want ordered from first to last, like you already have ( sortedArray
). 您已经有了一个数组,该数组具有要
sortedArray
排序的键,就像您已经拥有的( sortedArray
)一样。 Then you pass this array to the function. 然后,将此数组传递给函数。
The function then loop through the obj keys and get the first letter of it to check if it matches with the arra of keys, getting its index. 然后,该函数循环遍历obj键并获取它的第一个字母,以检查它是否与键的arra匹配,并获取其索引。 Based on the index, it sorts.
根据索引进行排序。
After the sort, then it creates a new obj and set the key and the value in the order it created in the sort
function used before 排序之后,它会创建一个新的obj,并按照在之前使用的
sort
函数中创建的顺序设置键和值。
Please, see the code to undertand it better. 请查看代码以更好地理解它。
var sortedArray = ['b', 'c', 'd', 'a']; var obj = { c: "see", a: "ay", b: "bee", d: "dee" }; function CustomOrderBy(keyOrder){ let keysSorted = Object.keys(obj).sort(function(keyA, keyB) { let idxA = keyOrder.indexOf(keyA[0]); let idxB = keyOrder.indexOf(keyB[0]); if (idxA > idxB){ return 1 }else if(idxA < idxB){ return -1 }else{ return 0; } }); let sorted = {}; for (var key of keysSorted){ if (obj[key] != null){ sorted[key] = obj[key]; } } return sorted; } console.log(CustomOrderBy(sortedArray))
Use custom sorter that uses indexOf()
使用使用
indexOf()
自定义排序器
var sortedArray = ['b', 'c', 'd', 'a']; var obj = { c: "see", a: "ay", b: "bee", d: "dee" }; var keys = Object.keys(obj).sort(function(a, b) { // TODO - cases where not in sortedArray return sortedArray.indexOf(a) - sortedArray.indexOf(b) }); console.log(keys)
Pardon me asking but if the relation between the sort order and the object is one to one why don't we do something like this (starting from the sort order array): 请原谅,但如果排序顺序和对象之间的关系是一对一的,为什么我们不做这样的事情(从排序顺序数组开始):
var myObject = {c: "see", a: "ay", b: "bee", d: "dee"}; var sortOrder = ['b','c','d','a']; const mySort = (obj, order) => order.reduce((r,c) => (r[c] = obj[c], r), {}) console.log(mySort(myObject, sortOrder))
It would seem that it would be quite more concise and simpler since it uses only one reduce . 由于它仅使用一个reduce ,因此看起来会更加简洁和简单。
you can create a function like i did below. 您可以像下面一样创建一个函数。 and pass your object it will return sorted object to you.
并传递您的对象,它将返回排序后的对象给您。
var obj = { c: "see", a: "ay", b: "bee", d: "dee" }; function sortObject(obj) { var keys = []; var outputObj = {}; for (key in obj) { keys.push(key); } keys.sort(); for(var i=0; i<keys.length; i++){ outputObj[keys[i]] = obj[keys[i]]; } return outputObj; } console.log(sortObject(obj));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.