使用纯JS或Lodash对基于数组的集合键进行排序

时间:2018-07-26 07:19:25

标签: arrays sorting collections lodash

我想基于数组productsorder集合键进行排序。我期望的输出像expecting。有人在纯JS或Lodash库中有简单的解决方案吗?

您可以从以下位置找到源代码 repl.it

谢谢

const _ = require('lodash')

var products = [
  {cgst: "18", item: "UPS V Guard Slender 1450", price: "2800", sgst: "18", stock: 2},
  {cgst: "9", item: "UPS V Guard Prime 1450", price: "6000", sgst: "9", stock: 30}
]
var order = ['item', 'price', 'cgst', 'sgst', 'stock']

// Expecting output
var expecting = [
  {item: "UPS V Guard Slender 1450", price: "2800", cgst: "18", sgst: "18", stock: 2},
  {item: "UPS V Guard Prime 1450", price: "6000", cgst: "9", sgst: "9", stock: 30}
]

1 个答案:

答案 0 :(得分:1)

您的问题实际上是排序CSV字段,而不是对象属性。 Papa.unparse()方法接受带有fieldsdata的对象。您可以将订单传递给它:

var products = [
  {cgst: "18", item: "UPS V Guard Slender 1450", price: "2800", sgst: "18", stock: 2},
  {cgst: "9", item: "UPS V Guard Prime 1450", price: "6000", sgst: "9", stock: 30}
]
var order = ['item', 'price', 'cgst', 'sgst', 'stock']

var csv = Papa.unparse({
	fields: order,
	data: products
});

console.log(csv);
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/4.5.0/papaparse.min.js"></script>

如果您确实需要订单对象属性的订单:

您可以Array.map()_.pick()来以正确的顺序获取对象属性。

注意::ES6对象属性中的命令有顺序,但有一些怪癖。参见此article

var products = [
  {cgst: "18", item: "UPS V Guard Slender 1450", price: "2800", sgst: "18", stock: 2},
  {cgst: "9", item: "UPS V Guard Prime 1450", price: "6000", sgst: "9", stock: 30}
]
var order = ['item', 'price', 'cgst', 'sgst', 'stock']

// Expecting output
var expecting = [
  {item: "UPS V Guard Slender 1450", price: "2800", cgst: "18", sgst: "18", stock: 2},
  {item: "UPS V Guard Prime 1450", price: "6000", cgst: "9", sgst: "9", stock: 30}
]

var result = products.map(o => _.pick(o, order))

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>