let num = 2;
let obj = {1:'',2:'',3:''};
//结果:{1:'',2:'',3:''} => {1:'',2:''}
//方法1:组装新的
let objNew = {}
for(let i=0;i<num;i++){
objNew[i+1] = obj[i+1];
}
// console.log('----',objNew)
//方法2:组装新的
let objNew2 = {};
for(let key in obj){
if(key <= num) objNew2[key] = obj[key];
}
//方法3:截取
//转二维数组[[1:''],[2:'']]
let res = Object.entries(obj).slice(0,num);
//二维数组转对象{1:'',2:''}
let objNew2 = Object.fromEntries(res);
console.log(objNew2)
Js截取对象
于 2023-05-11 14:40:18 首次发布