【问题标题】:How do I move inside of a dynamic object in javascript using just the keys that are saved in an array?如何仅使用保存在数组中的键在 javascript 中的动态对象内部移动?
【发布时间】:2019-01-14 20:38:16
【问题描述】:

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

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

【问题讨论】:

    标签: javascript arrays for-loop javascript-objects


    【解决方案1】:

    使用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)

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 我知道值的确切位置,但问题是它存储在一个数组中,当我尝试对其进行循环时,它返回一个字符串,我如何将字符串与对象连接起来?还是我应该改变存储位置的方式?谢谢
      • 好的,如果我理解正确的话,带有键的数组是动态生成的,您需要使用它来获取对象中的值吗?如果是这种情况,最简单的方法是:let result = myObject[myarray[0]][myarray[1]][myarray[2]]['inside']
      猜你喜欢
      • 2014-06-28
      • 2022-08-22
      • 2019-06-20
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      相关资源
      最近更新 更多