【问题标题】:Index an object multiple levels deep with one variable用一个变量索引一个对象的多层次深度
【发布时间】:2018-05-12 09:07:59
【问题描述】:

我有一个对象:

object.day.time

我需要在哪里访问 time 属性。

由于函数的性质,我只能访问基础对象。即。

function access(property){
    let item = object[property]
    // Do a lot of stuff with item
}

我不想重写函数,因为主要用例是访问一层深的对象。 IE。天属性。有什么办法可以使这项工作?

我唯一能想到的是:

property = [['day']['time']]

但这没有用。

编辑:我最初将对象作为访问参数,这是错误的。在那种情况下,我可以将 object.day 作为值传递

【问题讨论】:

  • 如果你只想使用你的access 函数,你必须重写它,至少一点。现在,您不能指望访问第二级,因为正如您所说,它仅针对主要用例设计,即一级对象。
  • 你不能这样叫access吗:access(object.day, 'time')
  • 糟糕。抱歉,我不是故意将对象作为参数。

标签: javascript arrays object


【解决方案1】:

您可以在某个时候这样做以访问此 time 属性:

var object = {
   day: {
      time: (new Date()).getTime()
   }
};

var properties = ["day","time"];

function access(object,properties){
   for(var index=0; index < properties.length; index++){
      // go to deeper into object until your reached time 
      object = object[properties[index]];
   }
   // here we have reached time and can do something with it or just returning it
   return object;
}

console.log(access(object,properties));

希望对你有所帮助。

【讨论】:

    【解决方案2】:

    当你调用这个函数时,传递 object.day 而不是仅仅传递基础对象,这意味着函数中的对象已经是 object.day,所以如果你做 object.time,你应该得到值。

    【讨论】:

      猜你喜欢
      • 2016-12-20
      • 2013-08-03
      • 2013-10-11
      • 1970-01-01
      • 2018-04-14
      • 1970-01-01
      • 1970-01-01
      • 2015-03-17
      • 2020-09-24
      相关资源
      最近更新 更多