简体   繁体   English

使用排序数组对对象键进行排序

[英]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: 像这样:

  1. 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. 然后,将此数组传递给函数。

  2. 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. 根据索引进行排序。

  3. 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.

相关问题 重新排列javascript对象 - 使用.sort()的键不会保留在正在排序的数组上 - Rearrange javascript object - keys using .sort() are not kept as on the array which is being sorted 基于数组排序对象以生成排序数组 - sort object base on array to produce sorted array 基于另一个键数组对对象数组进行排序 - Sort object array based on another array of keys lodash-根据对象的键将对象转换为排序的数组 - lodash - convert an object into a sorted array based on the keys of the object 根据属性对 object 中的数组进行排序,并返回排序后的初始 object - Sort array from object based on a property and return the sorted initial object 如果多个键具有相同的值,则按值排序 JavaScript Object 然后键(按字母顺序)。 按顺序返回排序的键 - Sort JavaScript Object by value and then key(alphabetically) if multiple keys has same value. Return sorted keys in order 对javascript中的某些键的对象数组进行排序 - Sort array of object for some keys in javascript 变异对象以将值排序为数组中的键 - mutate object to sort values to keys in an array Javascript根据另一个数组通过键对对象排序? - Javascript sort an object by keys based on another Array? 使用多个键排序数组对象:Javascript - Sort Array Object with Multiple Keys: Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM