如果我有一个JavaScript对象,如:

var list = {
  "you": 100, 
  "me": 75, 
  "foo": 116, 
  "bar": 15
};

是否有一种方法可以根据值对属性进行排序?最后得到

list = {
  "bar": 15, 
  "me": 75, 
  "you": 100, 
  "foo": 116
};

当前回答

另一个关于Object的例子。值、sort()和展开运算符。

var paintings = {
    0: {
        title: 'Oh my!',
        year: '2020',
        price: '3000'
    },
    1: {
        title: 'Portrait V',
        year: '2021',
        price: '2000'
    },
    2: {
        title: 'The last leaf',
        year: '2005',
        price: '600'
    }
}

我们使用object .values将对象转换为对象数组:

var toArray = Object.values(paintings)

然后我们对数组进行排序(按年份和价格),使用spread操作符使原始数组不可变,并使用sort()方法对数组进行排序:

var sortedByYear = [...toArray].sort((a, b) => a.year - b.year)
var sortedByPrice = [...toArray].sort((a, b) => a.price - b.price)

最后,我们生成新的排序对象(同样,使用展开运算符来保持以[x: number]为键的对象的object的原始形式):

var paintingsSortedByYear = {
    ...sortedByYear
}

var paintingsSortedByPrice = {
    ...sortedByPrice
}

希望这对你有所帮助!

其他回答

以防万一,有人正在寻找保持对象(键和值),使用@Markus R和@James Moran注释的代码引用,只需使用:

var list = {"you": 100, "me": 75, "foo": 116, "bar": 15};
var newO = {};
Object.keys(list).sort(function(a,b){return list[a]-list[b]})
                 .map(key => newO[key] = list[key]);
console.log(newO);  // {bar: 15, me: 75, you: 100, foo: 116}

这里还有一个例子:

函数sortObject(obj) { Var arr = []; var支撑; For (prop in obj) { if (obj.hasOwnProperty(prop)) { arr.push ({ “关键”:道具, “价值”:obj(道具) }); } } 加勒比海盗。排序(函数(a, b) { 返回a.value - b.value; }); 返回arr;//返回数组 } Var列表= { 车:300, 自行车:60岁 摩托车:200, 飞机:1000, 直升机:400, 火箭:8 * 60 * 60 }; var arr = sortObject(list); console.log (arr);

打印稿

下面的函数根据值或值的属性对对象进行排序。如果你不使用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 maxSpeed = {
    car: 300, 
    bike: 60, 
    motorbike: 200, 
    airplane: 1000,
    helicopter: 400, 
    rocket: 8 * 60 * 60
};
let sortable = [];
for (var vehicle in maxSpeed) {
    sortable.push([vehicle, maxSpeed[vehicle]]);
}

sortable.sort(function(a, b) {
    return a[1] - b[1];
});

// [["bike", 60], ["motorbike", 200], ["car", 300],
// ["helicopter", 400], ["airplane", 1000], ["rocket", 28800]]

有了数组之后,就可以按照自己喜欢的顺序从数组重新构建对象,从而完全实现您想要做的事情。这在我所知道的所有浏览器中都可以工作,但它将依赖于一个实现的怪癖,并且随时可能崩溃。永远不要假设JavaScript对象中元素的顺序。

let objSorted = {}
sortable.forEach(function(item){
    objSorted[item[0]]=item[1]
})

在ES8中,你可以使用object .entries()将对象转换为数组:

const maxSpeed = { 车:300, 自行车:60岁 摩托车:200, 飞机:1000, 直升机:400, 火箭:8 * 60 * 60 }; const sortable = Object.entries(maxSpeed) .sort([,a],[,b]) => a-b) .reduce((r, [k, v]) =>({…R, [k]: v}), {}); console.log(合适的);


在ES10中,你可以使用object. fromentries()将数组转换为对象。然后代码可以简化为:

const maxSpeed = { 车:300, 自行车:60岁 摩托车:200, 飞机:1000, 直升机:400, 火箭:8 * 60 * 60 }; const sortable = Object.fromEntries( Object.entries(maxSpeed).sort(([,a],[,b]) => a-b) ); console.log(合适的);

如果我有一个这样的对象,

var dayObj = {
              "Friday":["5:00pm to 12:00am"] ,
              "Wednesday":["5:00pm to 11:00pm"],
              "Sunday":["11:00am to 11:00pm"], 
              "Thursday":["5:00pm to 11:00pm"],
              "Saturday":["11:00am to 12:00am"]
           }

我想按天排序,

我们应该先有daySorterMap,

var daySorterMap = {
  // "sunday": 0, // << if sunday is first day of week
  "Monday": 1,
  "Tuesday": 2,
  "Wednesday": 3,
  "Thursday": 4,
  "Friday": 5,
  "Saturday": 6,
  "Sunday": 7
}

初始化一个单独的对象sortedDayObj,

var sortedDayObj={};
Object.keys(dayObj)
.sort((a,b) => daySorterMap[a] - daySorterMap[b])
.forEach(value=>sortedDayObj[value]= dayObj[value])

你可以返回sortedDayObj