/** * 递归查找指定值的复杂多维数组,返回该值的索引路径;可以用来判断一个格式乱七八糟的数组里是否包含某个值,比对对象:数组内的 纯字符串元素、对象类型的值 * @param {object} arr 要查找的数组 * @param {string} val 要查找的值 * @param {string} key 要查找的值对应的键 [可选] * @return {array} index 返回索引路径 */ const search_obj_key = function (arr, val, position) { let idx_path = ''; function _foreach (arr, val, position) { var temp = ''; arr.forEach((item, index) => { temp = position ? position + ',' + index : index; _findValue(item, index, temp); if (Object.prototype.toString.call(item) == '[object Object]') { let _array = Object.values(item); for(var arr_idx in _array){ _findValue(_array[arr_idx], index, temp); } } if (Object.prototype.toString.call(item) == '[object Array]') { _foreach(item, val, temp); } }) } function _findValue (item, index, temp) { if (item === val) { idx_path = temp; return; } else if (Object.prototype.toString.call(item) == '[object Array]') { _foreach(item, val, temp); } else if (Object.prototype.toString.call(item) == '[object Object]') { let _array = Object.values(item); for(var arr_idx in Object.values(item)){ _findValue(_array[arr_idx], index, temp); } } } _foreach(arr, val, position); if(!idx_path){ return false; } return idx_path.toString().split(',').map((v)=>{return parseInt(v)}); } let a = search_obj_key(data, 'block'); console.log(a)