简体   繁体   English

对对象数组进行排序,并从对象返回特定值的数组

[英]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: 为了使它成为单一的事实来源,我制作了一个id-product地图,看起来像这样:

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. 这里的一切都运行正常,排序的结果将是一个对象数组,为了得到id我正在使用map函数。

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. 现在问题是我要迭代三次(第一次获取对象值,第二次是排序,第三次是映射id),我想知道在数组排序时是否有更好的方法来获取ID。

You could order the keys of the handed over object, to get an array of id . 你可以订购移交对象的密钥,以获得一个id数组。

If you need the ìd property of the objects, you could map the values of the outer object with id property. 如果你需要的ìd对象的属性,您可以在外部对象的值与映射id属性。

 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); 

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

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