This question already has answers here:
Change position of object properties by matching other array
                            
                                (2个答案)
                            
                    
                    
                        Does ES6 introduce a well-defined order of enumeration for object properties?
                            
                                (3个答案)
                            
                    
                9个月前关闭。
        

    

我有一个JavaScript对象,例如:

{
  a: 3,
  b: 10,
  c: 2,
  d: 7,
}


我有一个包含属性名称的字符串表示形式的数组:

[ "c", "b", "a", "d" ]


如何重新排列对象,以使属性以与数组中相同的顺序排列,例如:

{
  c: 2,
  b: 10,
  a: 3,
  d: 7,
}


任何帮助表示赞赏!

最佳答案

尽管ECMAScript-6改进了该功能,但是众所周知,对象属性仍然是无序的。解决此问题的一种方法是使用可以记住原始密钥插入顺序的Map。



    const obj = { a: 3, b: 10, c: 2, d: 7 };
const arr = ["c", "b", "a", "d"];

const res = new Map(arr.map(e => [e, obj[e]]));

for (let [key, value] of [...res]) {
  console.log(key, value);
}





for...of循环仅用于显示实际的Map,因为它们未在Stack Snippets控制台上显示。)

10-07 16:34
查看更多