简体   繁体   中英

Sort array of objects and return array of specific values from the object

I have an array of objects(product list), and I am implementing the sorting logic to it. In order to make it a single source of truth, I made a id-product map, which looks something like this:

const prodsMap = {
  1 : {
    id : 1,
    name : 'abc',
    price : 4
  },
  2 : {
    id : 2,
    name : 'aac',
    price : 3
  }
}

Now in order to sort products I am doing this:

function sortString(data, propName) {
  return data.sort((obj1, obj2) => {
    const val1 = obj1[propName]
    const val2 = obj2[propName]

    if (val1 < val2) {
      return -1
    }

    if (val1 > val2) {
      return 1
    }

    return 0
  })
}

Calling the function like this:

const prods = sortString(Object.values(prodsMap), 'name')

Everything works fine here, the result of sorting will be an array of objects, in order to get the id's I am using map function.

Now the problem is that I've to iterate thrice(first to get object values, second to sort and third time to map id's), I was wondering if there is a better way to get only ID's when the array gets sorted.

You could order the keys of the handed over object, to get an array of id .

If you need the ìd property of the objects, you could map the values of the outer object with id property.

 const prodsMap = { 1 : { id : 1, name : 'abc', price : 4 }, 2 : { id : 2, name : 'aac', price : 3 } } function sortString(data, propName) { return Object.keys(data).sort((a, b) => { const val1 = data[a][propName]; const val2 = data[b][propName]; if (val1 < val2) { return -1; } if (val1 > val2) { return 1; } return 0; }); } const prods = sortString(prodsMap, 'name'); console.log(prods); 

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