methuselah
methuselah

Reputation: 13206

Sort object by key whilst retaining present values to match order of array

I have two objects. One in is in the format (footerMenuOptions):

[{Home: true}, {About: false}, {Features: false}, {Contact: false}] 

The second is in the format (this.navbarMenuOptions):

["Home", "About", "Features", "Contact"]

At times, the order of the second object (this.navbarMenuOptions) will change, to lets say:

["About", "Home", "Features", "Contact"]

I want the first objects order (footerMenuOptions) to change to be able to reflect this (i.e. the keys), but the values to remain intact).

In the case where the key-value pair does not exist, it should just be created with a default value of false (i.e. if this.navbarMenuOptions has a new entry).

What would be the most performant way of accomplishing this:

Code is as follows:

toggleFooterMenuOptionVisibility(index: number) {
   // Some other stuff happens beforehand which isn't important
   footerMenuOptions = this.sortFooterMenuOptions(footerMenuOptions);
}

sortFooterMenuOptions(footerMenuOptions) {
   // this.navbarMenuOptions is a global variable so it doesn't need to be passed in
   return footerMenuOptions;
}

Upvotes: 0

Views: 662

Answers (1)

Eldar
Eldar

Reputation: 10790

You can use your main object's keys and get indexes from second array and sort your object's keys by these indexes like below:

var arr1 = {
  Home: true,
  About: false,
  Features: false,
  Contact: false
}



var arr2 = ["About", "Home", "Features", "Contact"];
const ordered = {};
Object.keys(arr1).sort((a, b) => {
  return arr2.indexOf(a) - arr2.indexOf(b);
}).forEach(r => ordered[r] = arr1[r]);

console.log(ordered);

I assumed your object has 1 key or the first key is the same with values in the second array. So if we apply it to your example it should become like this :

sortFooterMenuOptions(unsortedFooterMenuOptions) {
  const sortedFooterMenuOptions = {};
  Object.keys(unsortedFooterMenuOptions)
    .sort((a, b) => {
      return this.navbarMenuOptions.indexOf(a) - this.navbarMenuOptions.indexOf(b);
    }).forEach(r => sortedFooterMenuOptions[r] = unsortedFooterMenuOptions[r]);
  return sortedFooterMenuOptions;
}

Upvotes: 1

Related Questions