1、对象key的遍历,及其他操作
场景1:将obj对象的所有属性值为 null 的改为'------',放入新newObj
场景条件:
obj = {
name: 'John Doe',
age: null,
address: '1234 Street',
phone: null
}场景结果:
newObj = {
name: 'John Doe',
age: '------',
address: '1234 Street',
phone: '------'
}代码示例1:(该方法会修改原始对象)
function replaceNullWithDash(obj) { // 使用Object.keys()获取对象的所有键 Object.keys(obj).forEach(key => { // 检查当前键对应的值是否为null if (obj[key] === null) { // 如果是,则将其更改为'------' obj[key] = '------'; } }); return obj; } // 示例对象 let obj = { name: 'John Doe', age: null, address: '1234 Street', phone: null }; // 调用函数 newObj = replaceNullWithDash(obj); console.log(newObj);
代码示例2:(该方法会创建一个新对象,原对象保持不变)
function replaceNullWithDashAndReturnNew(obj) { // 使用扩展运算符(...)和Object.fromEntries()来创建一个新对象 return Object.fromEntries( Object.entries(obj).map(([key, value]) => [key, value === null ? '------' : value]) ); } // 示例对象 let obj = { name: 'John Doe', age: null, address: '1234 Street', phone: null }; // 调用函数并获取新对象 let newObj = replaceNullWithDashAndReturnNew(obj); console.log(newObj);
方法解析:
- Object.entries()方法:获取对象的键值对数组
- map()方法:遍历数组,将值为null的项的值更改为'------'
- Object.fromEntries()方法:将键值对数组转换回对象
2、判断数组对象的深度
场景2:深度遍历arr数组,当存在对象depth属性的值为3时,立即return出去
场景条件:
arr=[
{ id:1, depth:1, children:[ { depth:2, children:null }, { depth:2, children:{ depth:3, children:null } }, ] },
{ id:2 depth:1, children:[ { depth:2, children:{ depth:3, children:null }, }, { depth:2, children:null }, ] }
]
代码示例:
function findDepthThree(arr) { for (let item of arr) { if (item.depth === 3) { return true; // 立即返回true,因为找到了depth为3的对象 } if (item.children && Array.isArray(item.children)) { // 递归检查children数组中的每个元素 if (findDepthThree(item.children)) { return true; // 如果在children中找到了depth为3的对象,则立即返回true } } } return false; // 如果没有找到depth为3的对象,则返回false } // 示例数组 const arr = [ { id: 1, depth: 1, children: [ { depth: 2, children: null }, { depth: 2, children: [ { depth: 3, children: null } ] }, ] }, { id: 2, // 注意:这里缺少了一个逗号 depth: 1, children: [ { depth: 2, children: [{ depth: 3, children: null }], }, { depth: 2, children: null }, ] }, ]; // 调用函数 console.log(findDepthThree(arr));//true