本文主要是介绍面试专题:如何对对象的部分属性按序访问,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
编程题:
如下所示,对象有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;
}
这篇关于面试专题:如何对对象的部分属性按序访问的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!