简体   繁体   English

使用 JavaScript 对 JSON 中的对象数组进行排序

[英]Sort Array in Objects in JSON using JavaScript

I have a unmarshalled string as JSON output called message_obj as shown below.我有一个未编组的字符串作为名为 message_obj 的 JSON 输出,如下所示。 The string was unmarshalled using JSON.pasrse() function.该字符串是使用 JSON.pasrse() 函数解组的。 I now need to sort the cars in order of their mileage (from low to high).我现在需要按照里程(从低到高)对汽车进行排序。 Can someone please show how will that be possible as I am not sure how arrays inside object works in JavaScript?有人可以展示这是怎么可能的,因为我不确定对象内部的数组在 JavaScript 中是如何工作的吗?

{
    username: 'Bob',
    cars: [
      {
        Id: 'car1',
        company: 'bmw',
        mileage: 66
      },
      {
        Id: 'car2',
        company: 'audi',
        mileage: 67
      },
      {
        Id: 'car3',
        company: 'GM',
        mileage: 48
      },
      {
        Id: 'car4',
        company: 'Mercedes',
        mileage: 54
      }
    ]
  }
data.cars.sort((a, b) =>
      a.mileage > b.mileage ? 1 : b.mileage > a.mileage ? -1 : 0
    );

Code Sandbox: https://codesandbox.io/s/winter-breeze-qo1cdu?file=/src/App.js:0-694代码沙盒: https ://codesandbox.io/s/winter-breeze-qo1cdu?file=/src/App.js:0-694

You can use a sort function to sort based on mileage, by passing it with a function您可以使用排序函数根据里程进行排序,方法是将其与函数一起传递

 const x = { username: 'Bob', cars: [{ Id: 'car1', company: 'bmw', mileage: 66 }, { Id: 'car2', company: 'audi', mileage: 67 }, { Id: 'car3', company: 'GM', mileage: 48 }, { Id: 'car4', company: 'Mercedes', mileage: 54 } ] } x.cars.sort((a, b) => { return a.mileage - b.mileage; }); console.log(x);

credits - https://www.javascripttutorial.net/array/javascript-sort-an-array-of-objects/学分 - https://www.javascripttutorial.net/array/javascript-sort-an-array-of-objects/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM