我想创建一个函数来根据属性名称数组获取对象的属性
const getObjectProperty = (arr: string[], object: any) {
// this function needs to return the object property
}
预期结果:
假设我有这个对象
const object = {
id: 1,
info: {
name: "my name",
age: 21,
home: {
city: "New York",
address: "Street Name"
}
},
}
getObjectProperty(["info", "name"], object) // returns "my name"
getObjectProperty(["info", "name", "city"], object) // returns "New York"
getObjectProperty(["id"], object) // returns 1
getObjectProperty(["info", "salary"], object) // returns undefined
我怎样才能做到这一点?
请使用Array的reduce
const array = ["info", "name"]
const object = {
id: 1,
info: {
name: "my name",
age: 21
}
}
const val = array.reduce((acc, item) => acc[item], object)
console.log(val)
您可以通过使用for...of循环来迭代属性名称数组并访问对象的相应属性,从而根据属性名称数组获取对象的属性。
const array = ["info", "name"];
const object = {
id: 1,
info: {
name: "my name",
age: 21
}
};
let result = object;
for (const property of array) {
result = result[property];
}
console.log(result); // "my name"
请注意,此代码假定数组中的属性名称存在于对象中并遵循嵌套属性链。如果任何属性名称拼写错误或不存在于对象中,或者属性链被破坏,代码将抛出错误。
您可以使用数组索引访问。这是你要找的吗?如果不知道索引,请使用
Array.findIndex()
获取索引。
object[array[0]][array[1]];
const array = ["info", "name"]
const object = {
id: 1,
info: {
name: "my name",
age: 21
}
}
console.log(object[array[0]][array[1]]);