如何移动对象键

时间:2019-09-25 13:09:06

标签: javascript lodash javascript-objects

让我创建一个如下对象:

let refs = {
  'key1': {name: 'one'},
  'key2': {name: 'two'},
  'key3': {name: 'three'}
};

我想重新排序键。 例如:将“ key2”移到最后。 我该怎么办?

我尝试了以下解决方案,但没有效果。

let temp = refs['key2'];
delete refs['key2'];
let refsCloned = _.clone(refs);
refsCloned['key2'] = temp;

JsFiddle example

1 个答案:

答案 0 :(得分:0)

尝试一下:

let refs = {
      'key1': {name: 'one'},
      'key2': {name: 'two'},
      'key3': {name: 'three'}
    };
delete refs['key2'];
const newObj = {}
newObj.key2 = {name: 'two'}
const resultObj = {...refs, ...newObj}

console.log(resultObj)
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {min-height:100% !important; top:0;}