面试专题:如何对对象的部分属性按序访问
编程题:
如下所示,对象有N个属性,需要对其中的key1 - key5属性按序优先显示,其他属性则按原序显示
// 输入
const obj = {
...
key10: 'key10',
key4: 'key4',
key5: 'key5',
key2: 'key2',
key1: 'key1',
key3: 'key3',
...
}
// 输出
const obj = {
key1: 'key1',
key2: 'key2',
key3: 'key3',
key4: 'key4',
key5: 'key5',
key10: 'key10',
...
}
实现1: 直接赋值
function sortedObj0(){
const orderKey = ['key1', 'key2', 'key3', 'key4', 'key5'];
const sortedDetail = {};
orderKey.forEach(key => {
if (obj[key]) {
sortedDetail[key] = obj[key];
}
});
Object.keys(obj).forEach(key => {
if (!sortedDetail[key]) {
sortedDetail[key] = obj[key];
}
});
console.log(sortedDetail)
return sortedDetail
}
实现2:使用解构语法
function sortedObj1(){
const {key1, key2, key3, key4, key5, ...rest} = obj;
const result = {
key1,
key2,
key3,
key4,
key5,
...rest
}
console.log(result)
return result;
}
实现3: 使用数据排序
function sortedObj2() {
const orderKey = ['key1', 'key2', 'key3', 'key4', 'key5'];
const orderObjKey = Object.keys(obj).sort((a,b) => {
let indexA = orderKey.indexOf(a);
let indexB = orderKey.indexOf(b);
if (indexA === -1) indexA = Number.MAX_SAFE_INTEGER;
if (indexB === -1) indexB = Number.MAX_SAFE_INTEGER;
return indexA - indexB
})
const resultObj = {};
orderObjKey.forEach(key => {
resultObj[key] = obj[key]
})
console.log(resultObj)
return resultObj;
}