我正在尝试按下面的值以升序对数组中的对象进行排序,并获得所需的输出,如下所示: -
var arr = [{"DOA Qty":"0.000665921017598927382910198160","LOS%":"0","FID Valid EC By Part":"0.0041860443283016713761966","Interventions":"0"}]
所需输出 - 按值按升序排序:
var desiredarr =[{"LOS%":"0","Interventions":"0","DOA Qty":"0.000665921017598927382910198160","FID Valid EC By Part":"0.0041860443283016713761966"}]
let sorteddataarr: any = Object.values(arr[0]).sort(function (a, b) { return arr[a] - arr[b]; });
alert(JSON.stringify(sorteddataarr)); // not giving result
答案 0 :(得分:1)
a[1]-b[1]
== :ASEC
b[1]-a[1]
== :DESC
试试这个:
var obj =
{
"DOA Qty":"0.000665921017598927382910198160",
"LOS%":"0",
"FID Valid EC By Part":"0.0041860443283016713761966",
"Interventions":"0"
}
var entries = Object.entries(obj)
entries.sort(function(a,b){return a[1]-b[1]});
obj = {};
entries.map(function(item){
obj[item[0]] = item[1];
})
console.log(obj);
答案 1 :(得分:0)
也许以下内容会有所帮助,在执行Object.keys
或for something in ...
等操作时,对象的键不会按特定顺序给出,因为顺序对您很重要我转换了对象一个或多个键和值的数组:
var arr = [{"DOA Qty":"0.000665921017598927382910198160","LOS%":"0","FID Valid EC By Part":"0.0041860443283016713761966","Interventions":"0"}];
console.log(
arr.map(
object=>
Object.keys(object).map(
key=>[Number(object[key]),key]//your values are not numbers, maybe create better JSON
).sort(
([a],[b])=>a-b
)
//optional, if you rather have [key,value] .map(([value,key])=>[key,value]
)
)