我如何通过关键字获取对象。 我也希望在对象名称中获得包含“_score”的对象值 我尝试Object.key()但它没有得到孩子
我有这个对象
const data : {
name : "johny",
lname : "walker",
a_score : 30,
b_score : 40,
result : {
c_score : 50,
d_score : 60
}
}
我如何返回此数据
{
a_score : 30,
b_score :40,
c_score :50,
d_score :60
}
答案 0 :(得分:1)
您可以使用reduce()
方法为此创建递归函数。
const data = {"name":"johny","lname":"walker","a_score":30,"b_score":40,"result":{"c_score":50,"d_score":60}}
const pick = (obj, key) => {
return Object.keys(obj).reduce((r, e) => {
if (typeof obj[e] == 'object') Object.assign(r, pick(obj[e], key))
if (e.includes(key)) r[e] = obj[e]
return r;
}, {})
}
console.log(pick(data, '_score'))