通过字符串动态选择数组,然后通过它.map()

时间:2016-04-22 14:51:29

标签: javascript arrays object

让我们假设这是为了参数而动态传递的。但简而言之就是举例说明..

let myVar = "something"

let anything = [{abc: 123, def: 456},{abc: 123, def: 456}]
let nothing = [{abc: 123, def: 456},{abc: 123, def: 456}]
let something = [{abc: 123, def: 456},{abc: 123, def: 456}]
let everything = [{abc: 123, def: 456},{abc: 123, def: 456}]

现在我假设我可以通过方括号访问它,但它似乎并不适合我。实施例

[myVar].map(function(k,v){...})

上述行的希望是使用通过用户选择动态生成的字符串。将到达其他定义的数组,或转换为等效的

something.map(function(k,v){...})

1 个答案:

答案 0 :(得分:2)

它不会那样工作,要使用括号获取数组,您需要为该数组提供父对象,例如:

let myVar = "something"

let myObj = {
  anything: [{abc: 123, def: 456},{abc: 123, def: 456}],
  nothing: [{abc: 123, def: 456},{abc: 123, def: 456}],
  something: [{abc: 123, def: 456},{abc: 123, def: 456}],
  everything: [{abc: 123, def: 456},{abc: 123, def: 456}]
}

myObj[myVar].map(function(k,v){...})