业务场景:存在任意深度的map对象,每一层都可能存在需要的键值,现要取出做后续处理
开搞
const test = {
"A":"1",
"B":"2",
"C":{
"A":"1-2",
"D":"4"
}
}
// 判断是否为对象
const isObject = (obj: any) => {
return Object.prototype.toString.call(obj) === "[object Object]";
};
// 获取嵌套对象属性的值
const getValue = (data: any, target: string): any => {
let arr = [];
for (const key of Object.keys(data)) {
if (key === target) {
arr.push(data[key])
// return data[key];
}
if (isObject(data[key])) {
const result = getValue(data[key], target);
if (result) {
arr.push(result)
// return result;
}
}
}
return arr
};
console.log(getValue(test,"A"))
效果
注:如有需要自己拉平数组
注:如有需要自己提取属性