0

I have some data which looks like this:

var mydata =[{
    "493":{
        "name":"Name 1",
        "subhere":{
            "subhere1":2
        }
    },
    "673":{
        "name":"Name 2",
        "subhere":{
            "subhere1":20
        }
    }
}];

I want to get the keys value into a variable so I’ve done this:

var data = [];
for (var i = 0; i < mydata.length; i++) {       
    var obj = mydata[i];     
    for(var key in obj){
        var newObj = {      
            name: obj[key].name,
            y: obj[key].subhere.subhere1,
            id: i,
            test: obj[key]   
        };
        data.push(newObj);      
    }
}

If you look at the line that has test: obj[key] that’s the line I want to get the value of the key BUT when I console.log(this.test) I get Object { name="Name 1",…etc but it’s not giving me the 493 or 673

How can I get the key number?

2
  • you can conver string into integer using parseInt Commented Jul 19, 2016 at 13:01
  • for(var key in obj) which means that you are grabbing key in obj which means that key will be the object property (493,673) and obj[key] will be the value (Object { name="Name 1", ...etc) Commented Jul 19, 2016 at 13:06

1 Answer 1

5

If you look at the line that has “test: obj[key]” that’s the line I want to get the value of the key BUT when I console.log(this.test) I get “Object { name=“Name 1”,…etc” but it’s not giving me the “493” or “673”

Simply replace

  test: obj[key]   

with

   test: key

Since you are already having the key in variable key

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.