简体   繁体   中英

JavaScript: How do I pass a string argument to a function to use to sort an array of objects by the value of that string argument?

I am also working in React. I am trying to build a reusable sorting component, which sorts an array of objects by a property field. For example with an array of objects with properties like so:

let seed = [
    {
        name: 'John', age: '35', cars : '4', income: '35000'
   },
   {
        name: 'Johnnny', age: '15', cars : '0', income: '100'
   },
    {
        name: 'Mary', age: '45', cars : '41', income: '350000'
   },
]

I can write it like this to sort the array by the name property:

let sortedData = [...seed].sort((a, b) => (a.name > b.name ? 1 : -1));

What I would like to do is something like this:

function sortData(array, field) {
  array.sort((a, b) => (a.[field] > b.[field] ? 1 : -1))
}

But it doesn't look like this is valid syntax. How can I do this without writing a different sort of each property like:

let sortedData = [...seed].sort((a, b) => (a.age > b.age ? 1 : -1));

cars
income
and so on

Remove the dot from your accessor. You can use either bracket notation or dot notation for each key, not both.

 let seed = [ { name: 'John', age: '35', cars : '4', income: '35000' }, { name: 'Johnnny', age: '15', cars : '0', income: '100' }, { name: 'Mary', age: '45', cars : '41', income: '350000' }, ] function sortData(array, field) { return array.sort((a, b) => (a[field] > b[field] ? 1 : -1)) } let sortedData = sortData([...seed], "cars"); console.log(sortedData);
 .as-console-wrapper { max-height: 100% !important; top: auto; }

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