我有一个像这样的对象数组
let myObj =[{
"60+": 0.1413972485314015,
"18-29": 0.0832178903621611,
"40-49": 0.1033361204013377,
"30-39": 0.0835906328864075,
"Under 18": 0.1326368677036551,
"50-59": 0.1224973366151133
}]
我想对上述对象数组进行排序
let myObj =[{
"Under 18": 0.1326368677036551,
"18-29": 0.0832178903621611,
"30-39": 0.0835906328864075,
"40-49": 0.1033361204013377,
"50-59": 0.1224973366151133
"60+": 0.1413972485314015,
}]
我如何使用javascript实现这种排序?
答案 0 :(得分:2)
您可以为Under
和+
量词取一个偏移量,然后取该值,具体取决于排序位置。然后返回值的增量或偏移量的增量。
稍后,您可以使用已排序的键构建新对象。
var object = { "60+": 0.1413972485314015, "18-29": 0.0832178903621611, "40-49": 0.1033361204013377, "30-39": 0.0835906328864075, "Under 18": 0.1326368677036551, "50-59": 0.1224973366151133 },
keys = Object
.keys(object)
.sort((a, b) => {
function getV(s, side) {
var offset = { 'Under': -1, null: 0, '+': 1 }[s.match(/Under|\+/)],
value = s.match(/\d+/g)[offset && side];
return { value, offset };
}
var aa = getV(a, 1),
bb = getV(b, 0);
return aa.value - bb.value || aa.offset - bb.offset;
}),
newObject = Object.assign(...keys.map(k => ({ [k]: object[k] })));
console.log(newObject);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:0)
您不能直接做,您必须像这样更改结构,我认为修改后的结构也是有道理的。
let myObj =[{
"60": 0.1413972485314015,
"29": 0.0832178903621611,
"49": 0.1033361204013377,
"39": 0.0835906328864075,
"18": 0.1326368677036551,
"59": 0.1224973366151133
}]
let result = Object.keys(myObj[0]).sort((a,b)=> a-b).map(val=>({[val]:myObj[0][val]}));
console.log(result);
答案 2 :(得分:0)
您可以使用第一个字符进行排序,并考虑第一个字符是否为数字,
let myObj = [{
"60+": 0.1413972485314015,
"18-29": 0.0832178903621611,
"40-49": 0.1033361204013377,
"30-39": 0.0835906328864075,
"Under 18": 0.1326368677036551,
"50-59": 0.1224973366151133
}];
const ordered = {};
Object.keys(myObj[0]).sort(
function(a, b) {
if (isNaN(Number(a.charAt(0))))
return -1;
if (isNaN(Number(b.charAt(0))))
return 1;
return a.charAt(0) - b.charAt(0);
}
).forEach(function(key) {
ordered[key] = myObj[0][key];
});
console.log(ordered);