描述:var a = {a: {b: {c: 1}, d: [1,2]}, e: 's'} 输出 [{key: 'abc', value: 1}, {key: 'ad', value: [1,2]}, {key: 'e', value: 's'}]
this is my answer
function getVal(obj,k="",arr=[]){
for(var key in obj){
if(Object.prototype.toString.call(obj[key]) === "[object Object]"&&obj[key]!==null){
getVal(obj[key],k+key,arr)
}else{
arr.push({
key:k+key,
value:obj[key]
})
}
}
return arr;
}
getVal(a)
what's the better?
###function getVal(obj, key = '') {
return Object.entries(obj).map(item => {
return Object.prototype.toString.call(item[1]) === '[object Object]'
? getVal(item[1], key + item[0])
: { key: key + item[0], value: item[1] }
}).flat()
}
###也可以利用树的遍历。
function getVal(data) {
// 非plain对象视为叶子节点
if(Object.prototype.toString.call(data) !== '[object Object]') {
return [{
key: '',
value: data
}];
}
const result = [];
Object.keys(data).forEach(key => {
const childList = getVal(data[key]);
childList.forEach(child => {
child.key = key + child.key;
result.push(child);
})
})
return result;
}