Home > Software design >  Best way to re arrange array of object?
Best way to re arrange array of object?

Time:03-17

I have an array or object which will serve as columns for a table with a unique key

const list = [{
    key: "Name",
    textColor: "red"
  },{
    key: "Age",
    textColor: "green"
  },{
    key: "Occupation",
    textColor: "yellow"
}]

And, I have a list of ordering of columns in the table

const newOrder = ["Occupation", "Name", "Age"]

Now , how can i rearrange the list according to the newOrder without using nested loops. Also, these all are dyanamic, so its not just about the above mentioned three columns

Expected Output

const list = [{
    key: "Occupation",
    textColor: "yellow"
  },{
    key: "Name",
    textColor: "red"
  },{
    key: "Age",
    textColor: "green"
}]

CodePudding user response:

Your list can be reformatted to a regular javascript object in which key is the property name, and textColor is the value:

const toObject = kvps => Object.fromEntries(kvps.map(kvp => [ kvp.key, kvp.textColor ]));

With a given array of keys, you can pick values from that object like so:

const fromObject = (order, obj) => order.map(key => ({ key, textColor: obj[key] }));

Chain the two together, and you can reorder any list of key value pairs:

const list = [{
    key: "Name",
    textColor: "red"
  },{
    key: "Age",
    textColor: "green"
  },{
    key: "Occupation",
    textColor: "yellow"
}]


const toObject = kvps => Object.fromEntries(kvps.map(kvp => [ kvp.key, kvp.textColor ]));
const fromObject = (order, obj) => order.map(key => ({ key, textColor: obj[key] }));
const reorder = (order, kvps) => fromObject(order, toObject(kvps));


const newList = reorder(["Occupation", "Name", "Age"], list);

console.log(
  newList
)

Edit: if the sizes of your list and order arrays are small, you probably want to go with the much easier to read approach suggested by Jon Webb in one of the other answers.

  • Related