Renjith
Renjith

Reputation: 2451

Sort an collection keys base on Array with pure JS or with Lodash

I want to sort the products collection keys based on the Array order. And I'm expecting the output like expecting. Does anyone have an easy solution in pure JS or with Lodash library?

You can find the source code from repl.it

Thanks

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}
]

Upvotes: 0

Views: 145

Answers (1)

Ori Drori
Ori Drori

Reputation: 192507

Your problem is actually ordering the CSV fields, and not object properties. The Papa.unparse() method accepts an object with fields and data. You can pass the order to it:

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>

If you really need order object properties' order:

You can Array.map() with _.pick() to get the objects properties in the correct order.

Note: in ES6 object properties have an order, but it has some quirks. See this 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>

Upvotes: 1

Related Questions