如何访问对象内部的特定路径/地址?

问题描述

我遇到了一个问题,我想我可能在解决之前就已经知道了,但是我现在不记得了,也无法解决

假设我们有一个深几层的对象,这意味着它具有其他对象作为值,这些对象也具有某些值对象,依此类推。

现在我该如何创建一个函数,将对象传递给它并在其中进行地址处理,然后可以像下面这样访问函数中该位置的值:

const getValueAtAdress = (object,'country.city.rules') => {
return //here I need to return the value at object.country.city.rules.
}

我缺少明显的东西吗?

解决方法

您的代码显示了一个函数 declaration ,但是您不能在引号中声明参数名称

但是,您可以调用函数并传递字符串。

在这种情况下,您只需要将字符串拆分为一个数组,然后在该数组上循环,即可建立可传递给对象的“链接”字符串索引集。 String.split()Array.reduce()方法是关键。

let obj = {
  county: {
      city: {
        rules: "Strict"
      }
  }
};

const getValueAtAddress = (object,countyCityRules) => { 
  // Split the string at the dots to form an array...
  // The loop over that array and reduce it with an
  // accumulator that is then applied to the object.
  return countyCityRules.split(".").reduce((acc,cur) => acc[cur],obj);;
}

console.log(getValueAtAddress(obj,"county"));
console.log(getValueAtAddress(obj,"county.city"));
console.log(getValueAtAddress(obj,"county.city.rules"));

,

我以为是后代在这里提到,帮助我的是使用reduce的答案,而reduce正是我以前使用的答案,但是我不记得了:

我用于解决特定问题的示例:

let stateLocation = address.split('.').reduce((acc,state);