1

Consider an array

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

In order to get the value of round1 in first_data we use

myarray(firstdata).round1

So I need to loop through the rounds that are present in which i specify just round and concatenate the iteration value

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

which must return the values of the rounds in the array

  • 1
    Please add your original data to post and also the expected out clealy – Maheer Ali May 11 '19 at 06:46
  • 1
    Use `canddata[key]["round" + i]`. But, you are better off creating an array for `rounds` rather than 20 properties with `round` prefix – adiga May 11 '19 at 06:49
  • If you want the property using an expression then use [Bracket Notaion](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Bracket_notation). Like `canddata[key]["round" + i]`. – Maheer Ali May 11 '19 at 07:25
  • Its not a good idea to have properties names containing some kind of sequence like `round1,2,3...`. You should use arrays instead. `first_data:{rounds:['h','i',...'z']}`. – Maheer Ali May 11 '19 at 07:28
  • At first should understand what mean `myarray[firstdata].round+i`: by starting this code javascript will start to find round property in the `myarray[firstdata]` object, so if you have that property the javascript will add `i` to that value. it is easy you should just read about array object in javascript. that enough – vlad-grigoryan May 11 '19 at 08:30

1 Answers1

0

You can try following to get keys from the object dynamically

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]])
}
Harsh Makadia
  • 3,263
  • 5
  • 30
  • 42