如何在 javascript 中仅使用保存在数组中的键在动态对象内部移动?



这是我的例子。我在 Javascript 中有一个动态更改的对象。 在这种情况下,我想要"内部"属性的值,我知道该值位于a[something][anotherthing][inside]的地方。因为我将位置保存在数组["a","somethig", "anotherthing"]中。我的问题是如何使用数组中的键移动到该位置?已经尝试连接元素,最终结果是这样的myObject[a][somthing][anotherthing]但问题是它返回"undefined",因为它是一个字符串。是否有机会将其转换为对象或某种方法在对象中获得该位置?

var myarray = ['a', 'something', 'anotherthing'];
myObject = {
  a: {
    something: {
      anotherthing: {
        inside: 10
      }
    }
  },
  b: {
    insideb: {}
  }
}

使用 reduce 将数组减少到单个值。您将传入myObject作为起点(第二个参数(,然后使用此基本回调(第一个参数(:

(obj, itm) => obj[itm]

当你把它们放在一起时,它看起来像这样:

var myarray = ['a', 'something', 'anotherthing'];
myObject = {
  a: {
    something: {
      anotherthing: {
        inside: 10
      }
    }
  },
  b: {
    insideb: {
    }
  }
}
let result = myarray.reduce((obj, itm) => obj[itm], myObject)
console.log(result)
console.log(result.inside)

如果您知道值的确切位置:myObject['a']['somthing']['anotherthing'] 将为您提供值。

如果需要动态单步执行对象,可以使用: Object.keys(myObject).forEach(key => myObject[key]); 来获取顶级键。

最新更新