我需要按关键字对JavaScript对象进行排序。
因此如下:
{ 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' }
将变成:
{ 'a' : 'dsfdsfsdf', 'b' : 'asdsad', 'c' : 'masdas' }
我需要按关键字对JavaScript对象进行排序。
因此如下:
{ 'b' : 'asdsad', 'c' : 'masdas', 'a' : 'dsfdsfsdf' }
将变成:
{ 'a' : 'dsfdsfsdf', 'b' : 'asdsad', 'c' : 'masdas' }
当前回答
ES6-这是1内衬
var数据={zIndex:99,名称:“Ravan”,年龄:25岁,位置:“架构”,金额:'100k',经理:‘ammu’};console.log(Object.entries(data).sort().reduce((o,[k,v])=>(o[k]=v,o),{}));
其他回答
JavaScript对象1未排序。试图对它们进行“排序”是没有意义的。如果要迭代对象的财产,可以对键进行排序,然后检索关联的值:
变量myObj={“b”:“asdsadfd”,“c”:“masdasaf”,“a”:“dsfdsfsdf”},键=[],k、 i,len;for(myObj中的k){如果(myObj.hasOwnProperty(k)){按键.按键(k);}}keys.sort();len=按键长度;对于(i=0;i<len;i++){k=键[i];console.log(k+':'+myObj[k]);}
使用Object.keys幻想的替代实现:
变量myObj={“b”:“asdsadfd”,“c”:“masdasaf”,“a”:“dsfdsfsdf”},keys=对象键(myObj),i、 len=按键长度;keys.sort();对于(i=0;i<len;i++){k=键[i];console.log(k+':'+myObj[k]);}
1不要迂腐,但没有JSON对象。
// if keys are char/string
const sortObject = (obj) => Object.fromEntries(Object.entries(obj).sort( ));
let obj = { c: 3, a: 1 };
obj = sortObject(obj)
// if keys are numbers
const sortObject = (obj) => Object.fromEntries(Object.entries(obj).sort( (a,b)=>a-b ));
let obj = { 3: 'c', 1: 'a' };
obj = sortObject(obj)
伙计们,我简直惊呆了!当然,所有的答案都有些陈旧,但没有人提到排序的稳定性!所以请耐心等待,我会尽力回答这个问题,并在这里详细说明。所以我现在要道歉,这将是很多阅读。
由于是2018年,我将只使用ES6,Polyfills都可以在MDN文档中找到,我将在给定部分链接。
问题的答案:
如果你的键只是数字,那么你可以安全地使用Object.keys()和Array.protocol.reduce()来返回排序后的对象:
// Only numbers to show it will be sorted.
const testObj = {
'2000': 'Articel1',
'4000': 'Articel2',
'1000': 'Articel3',
'3000': 'Articel4',
};
// I'll explain what reduces does after the answer.
console.log(Object.keys(testObj).reduce((accumulator, currentValue) => {
accumulator[currentValue] = testObj[currentValue];
return accumulator;
}, {}));
/**
* expected output:
* {
* '1000': 'Articel3',
* '2000': 'Articel1',
* '3000': 'Articel4',
* '4000': 'Articel2'
* }
*/
// if needed here is the one liner:
console.log(Object.keys(testObj).reduce((a, c) => (a[c] = testObj[c], a), {}));
但是,如果您使用字符串,我强烈建议将Array.prototype.sort()链接到所有这些字符串中:
// String example
const testObj = {
'a1d78eg8fdg387fg38': 'Articel1',
'z12989dh89h31d9h39': 'Articel2',
'f1203391dhj32189h2': 'Articel3',
'b10939hd83f9032003': 'Articel4',
};
// Chained sort into all of this.
console.log(Object.keys(testObj).sort().reduce((accumulator, currentValue) => {
accumulator[currentValue] = testObj[currentValue];
return accumulator;
}, {}));
/**
* expected output:
* {
* a1d78eg8fdg387fg38: 'Articel1',
* b10939hd83f9032003: 'Articel4',
* f1203391dhj32189h2: 'Articel3',
* z12989dh89h31d9h39: 'Articel2'
* }
*/
// again the one liner:
console.log(Object.keys(testObj).sort().reduce((a, c) => (a[c] = testObj[c], a), {}));
如果有人想知道reduce的作用:
// Will return Keys of object as an array (sorted if only numbers or single strings like a,b,c).
Object.keys(testObj)
// Chaining reduce to the returned array from Object.keys().
// Array.prototype.reduce() takes one callback
// (and another param look at the last line) and passes 4 arguments to it:
// accumulator, currentValue, currentIndex and array
.reduce((accumulator, currentValue) => {
// setting the accumulator (sorted new object) with the actual property from old (unsorted) object.
accumulator[currentValue] = testObj[currentValue];
// returning the newly sorted object for the next element in array.
return accumulator;
// the empty object {} ist the initial value for Array.prototype.reduce().
}, {});
如果需要,这里是对单线的解释:
Object.keys(testObj).reduce(
// Arrow function as callback parameter.
(a, c) =>
// parenthesis return! so we can safe the return and write only (..., a);
(a[c] = testObj[c], a)
// initial value for reduce.
,{}
);
减少的文件:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce为什么在JavaScript返回语句中使用括号:http://jamesknelson.com/javascript-return-parenthesis/
为什么排序有点复杂:
简而言之,Object.keys()将返回一个数组,其顺序与我们使用普通循环得到的顺序相同:
const object1 = {
a: 'somestring',
b: 42,
c: false
};
console.log(Object.keys(object1));
// expected output: Array ["a", "b", "c"]
Object.keys()返回元素为字符串的数组对应于直接在对象上找到的可枚举财产。财产的顺序与循环给出的顺序相同手动覆盖对象的财产。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
侧记-您也可以在数组上使用Object.keys(),请记住索引将被返回:
// simple array
const arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']
但这并不像这些例子所显示的那样简单,现实世界中的对象可能包含数字、字母字符甚至符号(请不要这样做)。
下面是一个示例,所有这些都在一个对象中:
// This is just to show what happens, please don't use symbols in keys.
const testObj = {
'1asc': '4444',
1000: 'a',
b: '1231',
'#01010101010': 'asd',
2: 'c'
};
console.log(Object.keys(testObj));
// output: [ '2', '1000', '1asc', 'b', '#01010101010' ]
现在,如果我们对上面的数组使用Array.protocol.sort(),输出将发生变化:
console.log(Object.keys(testObj).sort());
// output: [ '#01010101010', '1000', '1asc', '2', 'b' ]
以下是文档中的引用:
sort()方法就地对数组的元素进行排序并返回阵列。排序不一定稳定。默认排序顺序是根据字符串Unicode代码点。排序的时间和空间复杂性无法保证取决于实现。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
您必须确保其中一个为您返回所需的输出。在现实生活中,如果你同时使用不同的信息输入(如API和数据库),人们往往会把事情搞混。
那有什么大不了的?
每个程序员都应该理解以下两篇文章:
就地算法:
在计算机科学中,就地算法是一种不使用辅助数据结构转换输入的算法。但是,允许为辅助变量提供少量的额外存储空间。当算法执行时,输入通常被输出覆盖。就地算法仅通过替换或交换元素来更新输入序列。不到位的算法有时被称为不到位或不到位。
所以基本上我们的旧阵列将被覆盖!如果出于其他原因想保留旧阵列,这一点很重要。所以请记住这一点。
排序算法
稳定排序算法以与它们出现在输入中。对某些类型的数据进行排序时,仅部分在确定排序顺序时检查数据的排序。例如在右边的卡片排序示例中,卡片正在排序而他们的诉讼却被忽视了。这允许多个不同的正确排序版本的可能性原始列表。稳定的排序算法选择其中之一,根据以下规则:如果两项比较相等,例如两张5卡,则它们的相对顺序将被保留,这样如果输入中的一个在另一个之前,它也会在前面另一个在输出中。
扑克牌中的一个稳定类型的例子。卡片分类时按稳定排序排序,两个5s必须保持相同的顺序在它们最初所在的排序输出中用非稳定排序,5s可能以相反的顺序结束在排序的输出中。
这表明排序是正确的,但它发生了变化。所以在现实世界中,即使排序是正确的,我们也必须确保得到我们期望的结果!这是非常重要的,请记住这一点。有关更多JavaScript示例,请查看Array.prototype.sort()-docs:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
很多人都提到“对象无法排序”,但在那之后,他们给了你一个可行的解决方案。矛盾,不是吗?
没有人提及这些解决方案为何奏效。它们是这样的,因为在大多数浏览器的实现中,对象中的值是按照添加它们的顺序存储的。这就是为什么如果您从排序的键列表中创建新对象,它将返回预期结果。
我认为我们可以再增加一个解决方案——ES5功能方式:
function sortObject(obj) {
return Object.keys(obj).sort().reduce(function (result, key) {
result[key] = obj[key];
return result;
}, {});
}
上述ES2015版本(格式为“一行”):
const sortObject = o => Object.keys(o).sort().reduce((r, k) => (r[k] = o[k], r), {})
上述示例的简短解释(如评论中所要求的):
Object.keys为我们提供了所提供对象(obj或o)中的键列表,然后我们使用默认排序算法对这些键进行排序,接下来使用reduce将数组转换回对象,但这次对所有键进行了排序。
在保留引用的同时递归排序键。
function sortKeys(o){
if(o && o.constructor === Array)
o.forEach(i=>sortKeys(i));
else if(o && o.constructor === Object)
Object.entries(o).sort((a,b)=>a[0]>b[0]?1:-1).forEach(e=>{
sortKeys(e[1]);
delete o[e[0]];
o[e[0]] = e[1];
});
}
例子:
let x = {d:3, c:{g:20, a:[3,2,{s:200, a:100}]}, a:1};
let y = x.c;
let z = x.c.a[2];
sortKeys(x);
console.log(x); // {a: 1, c: {a: [3, 2, {a: 1, s: 2}], g: 2}, d: 3}
console.log(y); // {a: [3, 2, {a: 100, s: 200}}, g: 20}
console.log(z); // {a: 100, s: 200}