Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ionic-framework/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取循环中嵌套对象的值_Javascript - Fatal编程技术网

Javascript 获取循环中嵌套对象的值

Javascript 获取循环中嵌套对象的值,javascript,Javascript,我有以下目标。一个字符串数组,可用于获取所需对象的键。我的问题是,我不知道如何获取循环中的嵌套属性 我的阵列: const arr = ["firstName", "age", "organization.name"] 我的目标: const obj = {id: 1, firstName: "John", lastName: "Smith", age: 20, organization: {i

我有以下目标。一个字符串数组,可用于获取所需对象的键。我的问题是,我不知道如何获取循环中的嵌套属性

我的阵列:

const arr = ["firstName", "age", "organization.name"]
我的目标:

const obj = {id: 1, firstName: "John", lastName: "Smith", age: 20, organization: {id: 40, name: "Contoso"}}
我的循环:

for(let i = 0; i < arr.length; i++){ console.log(obj[arr[i]) }

我可能有错误的方法,但无法给出正确的答案。

这里有一个解决方案

function getValue(o, k) {
  return k.split('.').reduce((r, e) => {
    if (!r) return r;
    else return r[e] || undefined;
  }, o);
}
这里是用法

console.log(arr.map(row => getValue(obj, row)));
这是结果

["John", 20, "Contoso"]
["John", 20, "Contoso"]