javascript - lodash SortBy 对象内容

标签 javascript node.js lodash

我有一个像这样的对象数组:

var quantityPricing = [ 
    { quantity: 1, cost: 0.5 }, 
    { quantity: 100, cost: 0.45 }, 
    { quantity: 1000, cost: 0.25 }, 
    { quantity: 500, cost: 0.35 }
];

我试图根据数量对这个数组的内容进行升序排序,所以我期望的结果应该是:

[
    { quantity: 1, cost: 0.5 },
    { quantity: 100, cost: 0.45 },
    { quantity: 500, cost: 0.35 },
    { quantity: 1000, cost: 0.25 }
]

因此我尝试使用 lodash 命令:

_.sortBy(quantityPricing, ['quantity']);

但不幸的是,函数返回的结果似乎只按数量的第一个数字排序,例如:

{
    "quantity": 1,
    "cost": 0.5
},
{
    "quantity": 100,
    "cost": 0.45
},
{
    "quantity": 1000,
    "cost": 0.25
},
{
    "quantity": 500,
    "cost": 0.35
}

我不明白为什么 500 排在最后,除非它只按第一位排序?因为一旦我的数组排序,500 应该在 100 之后。

如有任何帮助,我们将不胜感激。

最佳答案

Lodash sortBy 不会修改原始数组,它应该返回一个新数组。你打印的是原始数组吗?

使用此代码进行测试,它有效:

var arr = _.sortBy(quantityPricing, 'quantity');
console.log(arr);

结果:

[ { quantity: 1, cost: 0.5 },
  { quantity: 100, cost: 0.45 },
  { quantity: 500, cost: 0.35 },
  { quantity: 1000, cost: 0.25 } ]

关于javascript - lodash SortBy 对象内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40792701/

相关文章:

javascript - 如何修复由以下原因引起的 : Error in app/app. component.html:15:1:没有 RouterOutletMap 提供程序

node.js - 如果定义了属性,则从 Waterline 中的模型获取结果

javascript - _.upperFirst 的 lodash 奇怪行为

javascript - Node.js 服务器如何访问 ajax 请求的数据?

javascript - Puppeteer page.click(selector) 不响应 IFrame

javascript - 将 lodash 的 `_.pull` 转换为普通 JS?

javascript - 使用 lodash 过滤多个值?

javascript - MeteorJS 中的 Promise

javascript - Knockout JS : observableArray. splice(0) 不是克隆数组?

javascript - 检查对话框是否打开会抛出 "cannot call methods on dialog prior to initialization"错误