简体   繁体   中英

Sort Array in Objects in JSON using JavaScript

I have a unmarshalled string as JSON output called message_obj as shown below. The string was unmarshalled using JSON.pasrse() function. 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?

{
    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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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