递归检索对象中是否包含某个值 - yuzhouxiaogegit/blog GitHub Wiki

递归检索对象中是否包含某个值

方法名:isValueExist

参数:searchV (必传),当前需要检索的值为基本类型,(注意:不能是json和array)

参数:searchObj (必传),当前需要检索的对象,可以是json/array

参数:result,这个参数不用传入,返回值, result == true 表示检索到了,result == false 未检索到该值

介绍:递归检索对象中是否包含某个值

/*
  方法名:isValueExist
  参数:searchV (必传),当前需要检索的值为基本类型,(注意:不能是json和array)
  参数:searchObj (必传),当前需要检索的对象,可以是json/array
  参数:result,这个参数不用传入,返回值, result == true 表示检索到了,result == false 未检索到该值
  介绍:递归检索对象中是否包含某个值

*/
function isValueExist(searchV, searchObj, result = false) {
    function innerFun(searchV, searchObj) {
      for (let k in searchObj) {
        if ( searchObj[k] instanceof Object || searchObj[k] instanceof Array ) {
          innerFun(searchV, searchObj[k]);
        } else {
          if (searchObj[k] == searchV) {
            result = true;
          }
        }
      }
      return result
    }
    return innerFun(searchV, searchObj);
}
// isValueExist 方法调用示例
let tempSearchV = {"user":{"name":"zhanshan","goods":{"clothes":"T恤","color":"red","Hair":"blue"},"id":5,"sex":"男","age":61}};
console.log(isValueExist('T恤',tempSearchV),'isValueExist 方法调用示例') 

递归将多维数组扁平化为一维数组

方法名:handleArr

参数:handleV (必传),当前需要扁平化的索引数组

参数:resV ,这个参数不用传入,是处理后的结果

介绍:递归将多维数组转换为一维数组

 /* 方法名:handleArr 参数:handleV (必传),当前需要扁平化的索引数组 
    参数:resV ,这个参数不用传入,是处理后的结果 
    介绍:递归将多维数组转换为一维数组 
*/
function handleArr(handleV, resV = []) { 
  for (let k in handleV) { 
    if (handleV[k] instanceof Array) { 
      handleArr(handleV[k], resV); 
    } else { 
      resV.push(handleV[k]) 
    } 
  } return resV 
}
// handleArr 方法调用示例 
let tempArr = [1, 5, 89, [55, { "name": "zhanshan", "id": 5, "sex": "男", "age": 61 }, 8, [1, 5, 89, 859], 85, 6, 56, 59], 96, 56,]; 
console.log(handleArr(tempArr), 'handleArr 方法调用示例')

递归将多层json格式数据,转换为一层

方法名:handelJSON

参数:handleV (必传),当前需要扁平化的JSON数据

参数:resV ,这个参数不用传入,是处理后的结果

介绍:递归将多层json格式数据,转换为一层(注意,相同的key值会被覆盖)

 /* 
   方法名:handelJSON 
   参数:handleV (必传),当前需要扁平化的JSON数据
   参数:resV ,这个参数不用传入,是处理后的结果 
   介绍:递归将多层json格式数据,转换为一层(注意,相同的key值会被覆盖) 
 
   */
 function handelJSON(handleV, resV = {}) { 
   for (let k in handleV) { 
     if (handleV[k] instanceof Object) { 
       handelJSON(handleV[k], resV);
       } else { 
         resV[k] = handleV[k]
       } 
   } 
   return resV
 }
 // handelJSON 方法调用示例 
 let tempJSON = { "user": { "name": "zhanshan", "goods": { "clothes": "T恤", "color": "red", "Hair": "blue" }, "id": 5, "sex": "男", "age": 61 } };
 console.log(handelJSON(tempJSON), 'handelJSON 方法调用示例')