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

时间:2022-01-17 19:39:13

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。

1 个解决方案

#1


3  

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.

如果需要对象的“属性”,则可以使用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);

#1


3  

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.

如果需要对象的“属性”,则可以使用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);