我有一个关于如何在打字稿中的对象中动态获取id值的问题。我可以举一个例子:
输入对象如下:
station = {
id: "123123",
address: {
id: "asdfasd",
type: "street"
value: "asdfas"
},
station: {
id: "asdsdfsdfasd",
type: "trainstation"
value: "asdfsdfsas"
},
information: {
id: "asdsdfsdfasd",
school: {
id: "asdsdsdsfsdfasd",
type: "middleschool"
value: "asdfssdsddfsas"
}
}
}
如何动态获取父ID,如果给我一个诸如“ shool”的参数,那么我可以获得信息ID?
任何解决方案
答案 0 :(得分:0)
这是您要寻找的东西吗?
const station = {"id":"123123","address":{"id":"asdfasd","type":"street","value":"asdfas"},"station":{"id":"asdsdfsdfasd","type":"trainstation","value":"asdfsdfsas"},"information":{"id":"asdsdfsdfasd","school":{"id":"asdsdsdsfsdfasd","type":"middleschool","value":"asdfssdsddfsas"}}};
function getId(obj, key){
let id;
Object.keys(obj, key).forEach(x=>{
if(x == key){
id = obj[x].id; return id;
}
else{
if(typeof(obj[x]) == 'object'){ id = getId(obj[x], key)};
}
});
return id;
};
console.log(getId(station, 'school'));