[英]Sort object by key whilst retaining present values to match order of array
I have two objects.我有两个对象。 One in is in the format
(footerMenuOptions)
:格式之一是
(footerMenuOptions)
:
[{Home: true}, {About: false}, {Features: false}, {Contact: false}]
The second is in the format (this.navbarMenuOptions)
:第二个是格式
(this.navbarMenuOptions)
:
["Home", "About", "Features", "Contact"]
At times, the order of the second object (this.navbarMenuOptions)
will change, to lets say:有时,第二个对象
(this.navbarMenuOptions)
的顺序会改变,比如说:
["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).我希望第一个对象顺序
(footerMenuOptions)
改变以能够反映这一点(即键),但值保持不变)。
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).在键值对不存在的情况下,应该使用默认值 false 创建它(即如果
this.navbarMenuOptions
有一个新条目)。
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.我假设您的对象有 1 个键,或者第一个键与第二个数组中的值相同。 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; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.