简体   繁体   中英

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 (ie 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 (ie 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;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM