Вы можете использовать Object.entries()
для преобразования объекта в массив, затем используйте .slice()
и .concat()
, и, наконец, Object.fromEntries()
, чтобы вернуть ваш объект.
В приведенном ниже примере я также использовали Object.keys()
и .indexOf()
, чтобы найти индекс key
, но есть и другие решения.
let periods = {
"Su": 6,
"Mo": 10,
"Ma": 7,
"Ra": 18,
"Ju": 16,
"Sa": 19,
"Me": 17,
"Ke": 7,
"Ve": 20,
};
function rotateOrder(key, obj) {
let idx = Object.keys(obj).indexOf(key) // find the index of your key
let arr = Object.entries(obj) // this transform your object into an array
let newObj = Object.fromEntries( // this will recreate your object
arr.slice(idx) // get the ending part of the array, starting on key
.concat(arr.slice(0,idx)) // concatenate the beginning
)
return newObj
}
console.log(rotateOrder('Ju',periods))
Вы также можете использовать unshift
(с оператором спреда) вместо concat
. Я не знаю, какой из них работает лучше:
function rotateOrder(key, obj) {
let idx = Object.keys(periods).indexOf(key) // find the index of your key
let arr = Object.entries(periods) // this transform your object into an array
// move the ending part (starting from key) to the beginning
arr.unshift(...arr.splice(idx))
let newObj = Object.fromEntries(arr) // this will recreate your object
return newObj
}
Примечание из MDN веб-документов :
Начиная с ECMAScript 2015, объекты сохраняются порядок создания строковых и символьных ключей. В JavaScript движках, которые соответствуют ECMAScript 2015 spe c, итерирование по объекту только со строковыми ключами приведет к ключам в порядке вставки.