如何在JavaScript中对对象进行降序排序?输出需匹配示例格式
在JavaScript中实现对象的降序排序(保持指定输出格式)
需求说明
需要对给定的JSON数据中的products对象按指定字段(示例中为popularity)进行降序排序,最终输出格式需与原示例结构一致(products仍以键值对形式存在,且键对应产品的顺序为排序后的结果)。
实现步骤与代码
- 将
products对象转换为键值对数组(对象本身无法直接排序,需借助数组的排序方法) - 对数组按目标字段进行降序排序(注意将字符串类型的数字转为数值类型再比较)
- 将排序后的数组转回对象,保留排序后的键顺序
- 组合成完整的JSON结构,保留原数据中的
count字段
// 原数据 const originalData = { "count": 1000, "products": { "6834": { "subcategory": "mobile", "title": "Micromax Canvas Spark", "price": "4999", "popularity": "51936" }, "5530": { "subcategory": "mobile", "title": "Samsung Galaxy Grand Max", "price": "12950", "popularity": "48876" }, "4340": { "subcategory": "mobile", "title": "Apple iPhone 6", "price": "40999", "popularity": "46198" }, "4804": { "subcategory": "mobile", "title": "Samsung Galaxy Grand Prime", "price": "9286", "popularity": "45775" }, "5266": { "subcategory": "mobile", "title": "Micromax Canvas Nitro A311", "price": "7769", "popularity": "44273" }, "5629": { "subcategory": "mobile", "title": "Samsung Galaxy E7", "price": "15763", "popularity": "40345" } } }; // 按popularity降序排序products const sortedProducts = Object.fromEntries( Object.entries(originalData.products) .sort(([, productA], [, productB]) => { // 将字符串转为数值类型后比较,b减a实现降序 return parseInt(productB.popularity) - parseInt(productA.popularity); }) ); // 生成排序后的完整数据 const sortedData = { ...originalData, products: sortedProducts }; // 输出格式化后的JSON结果 console.log(JSON.stringify(sortedData, null, 2));
扩展说明
- 如果需要按其他字段(如
price)降序排序,只需将排序逻辑中的productB.popularity和productA.popularity替换为对应的字段即可 Object.fromEntries()是ES6+的方法,能保留数组转对象时的插入顺序,确保排序后的对象符合预期格式
内容的提问来源于stack exchange,提问作者MOHD ASIF
相关产品推荐
相关产品推荐

