如果我有一个JavaScript对象,如:
var list = {
"you": 100,
"me": 75,
"foo": 116,
"bar": 15
};
是否有一种方法可以根据值对属性进行排序?最后得到
list = {
"bar": 15,
"me": 75,
"you": 100,
"foo": 116
};
如果我有一个JavaScript对象,如:
var list = {
"you": 100,
"me": 75,
"foo": 116,
"bar": 15
};
是否有一种方法可以根据值对属性进行排序?最后得到
list = {
"bar": 15,
"me": 75,
"you": 100,
"foo": 116
};
当前回答
@marcusR回答的“箭头”版本供参考
var myObj = { you: 100, me: 75, foo: 116, bar: 15 };
keysSorted = Object.keys(myObj).sort((a, b) => myObj[a] - myObj[b]);
alert(keysSorted); // bar,me,you,foo
更新:2017年4月 返回一个上面定义的排序后的myObj对象。 const myObj ={你:100,我:75,foo: 116, bar: 15}; Const result = 种(myObj) .sort((a, b) => myObj[a] - myObj[b]) .reduce ( (_sortedObj, key) => ({ ……_sortedObj, (例子):myObj(例子) }), {} ); document . write (JSON.stringify(结果));
更新:2021年3月-对象。带有排序功能的条目(根据注释更新) const myObj ={你:100,我:75,foo: 116, bar: 15}; const result =对象 .entries (myObj) .sort((a, b) => a[1] - b[1]) .reduce((_sortedObj, [k,v]) => ({ ……_sortedObj, [k]: v }, {}) document . write (JSON.stringify(结果));
其他回答
找不到上面的答案,既工作又小,并支持嵌套对象(不是数组),所以我写了自己的一个:)工作与字符串和整数。
function sortObjectProperties(obj, sortValue){
var keysSorted = Object.keys(obj).sort(function(a,b){return obj[a][sortValue]-obj[b][sortValue]});
var objSorted = {};
for(var i = 0; i < keysSorted.length; i++){
objSorted[keysSorted[i]] = obj[keysSorted[i]];
}
return objSorted;
}
用法:
/* sample object with unsorder properties, that we want to sort by
their "customValue" property */
var objUnsorted = {
prop1 : {
customValue : 'ZZ'
},
prop2 : {
customValue : 'AA'
}
}
// call the function, passing object and property with it should be sorted out
var objSorted = sortObjectProperties(objUnsorted, 'customValue');
// now console.log(objSorted) will return:
{
prop2 : {
customValue : 'AA'
},
prop1 : {
customValue : 'ZZ'
}
}
打印稿
下面的函数根据值或值的属性对对象进行排序。如果你不使用TypeScript,你可以删除类型信息,将其转换为JavaScript。
/**
* Represents an associative array of a same type.
*/
interface Dictionary<T> {
[key: string]: T;
}
/**
* Sorts an object (dictionary) by value or property of value and returns
* the sorted result as a Map object to preserve the sort order.
*/
function sort<TValue>(
obj: Dictionary<TValue>,
valSelector: (val: TValue) => number | string,
) {
const sortedEntries = Object.entries(obj)
.sort((a, b) =>
valSelector(a[1]) > valSelector(b[1]) ? 1 :
valSelector(a[1]) < valSelector(b[1]) ? -1 : 0);
return new Map(sortedEntries);
}
使用
var list = {
"one": { height: 100, weight: 15 },
"two": { height: 75, weight: 12 },
"three": { height: 116, weight: 9 },
"four": { height: 15, weight: 10 },
};
var sortedMap = sort(list, val => val.height);
JavaScript对象中键的顺序是不保证的,所以我将排序并将结果返回为一个保留排序顺序的Map对象。
如果你想把它转换回Object,你可以这样做:
var sortedObj = {} as any;
sortedMap.forEach((v,k) => { sortedObj[k] = v });
找出每个元素的频率,并按频率/值进行排序。
Let response =["苹果","橘子","苹果","香蕉","橘子","香蕉","香蕉"]; 设frequency = {}; response.forEach(函数(项){ 频率[项目]=频率[项目]?频率[项]+ 1:1; }); console.log(频率); let intents = Object.entries(frequency) .sort((a, b) => b[1] - a[1]) . map(函数(x) { 返回x [0]; }); console.log(意图);
输出:
{ apple: 2, orange: 2, banana: 3 }
[ 'banana', 'apple', 'orange' ]
a = { b: 1, p: 8, c: 2, g: 1 }
Object.keys(a)
.sort((c,b) => {
return a[b]-a[c]
})
.reduce((acc, cur) => {
let o = {}
o[cur] = a[cur]
acc.push(o)
return acc
} , [])
输出= [{p: 8}, {c: 2}, {b: 1}, {g: 1}]
感谢@orad在TypeScript中提供了答案。现在,我们可以在JavaScript中使用下面的代码片断。
function sort(obj,valSelector) { const sortedEntries = Object.entries(obj) .sort((a, b) => valSelector(a[1]) > valSelector(b[1]) ? 1 : valSelector(a[1]) < valSelector(b[1]) ? -1 : 0); return new Map(sortedEntries); } const Countries = { "AD": { "name": "Andorra", }, "AE": { "name": "United Arab Emirates", }, "IN": { "name": "India", }} // Sort the object inside object. var sortedMap = sort(Countries, val => val.name); // Convert to object. var sortedObj = {}; sortedMap.forEach((v,k) => { sortedObj[k] = v }); console.log(sortedObj); //Output: {"AD": {"name": "Andorra"},"IN": {"name": "India"},"AE": {"name": "United Arab Emirates"}}