如何将对象的指定属性重新排列到属性列表末尾?
如何将对象的指定属性重新排列到属性列表末尾?
先给大家回顾下之前把指定属性移到对象属性列表顶部的做法,代码大概是这样的:
const raw = { a: 1, b: 2, // ...其他属性 y: 3, z: 4, }; const templateTop = { y: null, z: null, } const rearrangedTop = Object.assign(templateTop, raw); // 结果: // { // y: 3, // z: 4, // a: 1, // b: 2, // ...其他属性 // };
不过你现在关心的是怎么把某些属性移到列表末尾对吧?其实思路也很清晰:先把不需要挪到末尾的属性挑出来,再把要移到末尾的属性拼在后面就行。这里给你两种实现方式:
方式一:基础遍历写法
这种写法直观易懂,适合刚接触JS的朋友:
const raw = { a: 1, b: 2, c: 5, // 示例其他属性 d: 6, y: 3, z: 4, }; // 定义要移到末尾的属性数组 const bottomProps = ['a', 'b']; // 拆分属性到两个临时对象 const restProps = {}; const bottomTarget = {}; for (const key in raw) { if (bottomProps.includes(key)) { bottomTarget[key] = raw[key]; } else { restProps[key] = raw[key]; } } // 合并得到最终结果 const rearrangedBottom = { ...restProps, ...bottomTarget }; // 最终输出: // { // c: 5, // d: 6, // y: 3, // z: 4, // a: 1, // b: 2 // }
方式二:ES6+简洁写法
如果喜欢更简洁的函数式写法,可以用Object.entries和reduce来处理:
const raw = { a: 1, b: 2, c: 5, d: 6, y: 3, z: 4, }; // 用Set来存要移到末尾的属性,查找效率更高 const bottomProps = new Set(['a', 'b']); // 拆分属性条目 const [restEntries, bottomEntries] = Object.entries(raw).reduce( ([rest, bottom], [key, value]) => { return bottomProps.has(key) ? [rest, [...bottom, [key, value]]] : [[...rest, [key, value]], bottom]; }, [[], []] ); // 转换回对象 const rearrangedBottom = Object.fromEntries([...restEntries, ...bottomEntries]);
需要注意的是,这种方法依赖ES6及以后的对象属性遍历规则——规范里明确了自有属性会按插入顺序排列(数字类型的键除外),所以只要你的运行环境支持ES6+,这个方案就能稳定工作。
备注:内容来源于stack exchange,提问作者Ooker
相关产品推荐
相关产品推荐

