我的问题是,从javascript对象获取所有最后一个值的最佳方法是什么。 示例:给定任何对象(必须接受任何对象),但是例如:
const obj = {
"id": 1,
"name": "Leanne Graham",
"address": {
"street": "Kulas Light",
"geo": {
"lat": "-37.3159",
}
}
}
并且具有获取所有最后值的功能:
console.log( getAllLastValues(obj) );
预期结果是:
{
"id": 1,
"name": "Leanne Graham",
"street": "Kulas Light",
"lat": "-37.3159"
}
答案 0 :(得分:1)
您可以使用递归函数来使用reduce()
const obj = {
"id": 1,
"name": "Leanne Graham",
"address": {
"street": function() {
return 'Function works'
},
"geo": {
"lat": "-37.3159",
}
}
}
function getLast(data) {
return Object.keys(data).reduce(function(r, e) {
if (typeof data[e] == 'object' && data[e] !== "function") Object.assign(r, getLast(data[e]))
else if (typeof data[e] === "function") r[e] = data[e]()
else r[e] = data[e]
return r;
}, {})
}
console.log(getLast(obj))

更新:更复杂的数据结构。
const obj = {
"id": 1,
"name": "Leanne Graham",
"address": {
"street": function() {
return {
lorem: 'ipsum',
another: function() {
return 'one'
},
test: 'Test'
}
},
"geo": {
"lat": "-37.3159",
}
}
}
function getLast(data) {
return Object.keys(data).reduce(function(r, e) {
if (typeof data[e] == 'object' && data[e] !== "function") {
Object.assign(r, getLast(data[e]))
} else if (typeof data[e] === "function") {
if (typeof data[e]() === 'object') Object.assign(r, getLast(data[e]()))
else r[e] = data[e]()
} else {
r[e] = data[e]
}
return r;
}, {})
}
console.log(JSON.stringify(getLast(obj), 0, 4))