根据数组中的值重新排序对象中的 key/values

re order key/values in object based on values in array

刚找到这个

Sort JavaScript object by key

我正在尝试重新排序对象的 key/values 以匹配使用下划线的数组的值

输入

{
    'red':'one',
    'blue':'two',
    'green':'three'
}

要映射到的数组

['green','red','blue']

预期输出

{
    'green':'three',
    'red':'one',
    'blue':'two'
}

JS 对象没有内在顺序(Does JavaScript Guarantee Object Property Order?)。

不过,您可以使用数组来 "apply" 下订单。 . .使用与对象中的键匹配的条目创建数组(就像您看起来已经拥有的那样),然后,当您循环遍历数组时,引用对象中与数组中的当前值匹配的键。

for (var i = 0; i < theArray.length; i++) {
    if (theObject.hasOwnProperty(theArray[i]) {
        . . . do stuff with theObject[theArray[i]] . . .
    }
}

或者,您可以使用对象数组,这会为值提供固有顺序,但会对原始对象中的数据关系以及您访问该数据的方式产生一些影响。

[
    {'green':'three'},
    {'red':'one'},
    {'blue':'two'}
]