如何将字符串添加到数组的键并获取值

时间:2019-05-11 06:44:09

标签: javascript arrays reactjs

考虑数组

var myarray = 
{
first_data:{"round1":"h","round2":"i",...,"round20":"z"}
second_data:{"round1":"a","round2":"b",...,"round26":"z"}
}

为了获取first_data中round1的值 我们使用

myarray(firstdata).round1

所以我需要遍历存在的各个回合,在这些回合中我只指定回合并连接迭代值

for(var i=1;i<21;i++){
      console.log(myarray[firstdata].round+i)
}

必须返回数组中的回合值

1 个答案:

答案 0 :(得分:0)

您可以尝试按照以下步骤动态地从对象获取键

var myarray = 
{
first_data:{"round1":"h","round2":"i","round20":"z"},
second_data:{"round1":"a","round2":"b","round26":"z"}
}

var first = myarray.first_data
var totalKeys = Object.keys(myarray.first_data).length;
var keys = Object.keys(myarray.first_data);

for(let i=0; i < totalKeys; i++){
  console.log("keys is", keys[i])
console.log("Value is", first[keys[i]])
}