-1

So I have this rest call, which is returning this sample data.

var test = {
    "id": "testtset",
    "name": "sf-rg",
    "tags": {
        "Tag Set": "005",
        "User Name": "Bond"
    },
    "properties": {
        "provisioningState": "Succeeded"
    }
},
{
    "id": "365tset",
    "name": "Test365",
    "location": "us",
    "properties": {
        "provisioningState": "Succeeded"
    }
}

console.log(test.tags["User Name"]);

If I run this it will give me an error.

My object contain values for user name but not for all ID's.

Let's say if I just have one json object console.log(test.tags["User Name"]); this will work fine, But not for multiple data objects.

Does any one know how to resolve this issue?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Mag
  • 1

3 Answers3

1

Do it Like This.

var test =[
        {
        "id": "testtset",
        "name": "sf-rg",
        "tags": {
            "Tag Set": "005",
            "User Name": "Bond"
        },
        "properties": {
            "provisioningState": "Succeeded"
        }
    },
    {
        "id": "365tset",
        "name": "Test365",
        "location": "us",
        "properties": {
            "provisioningState": "Succeeded"
        }

    }]
console.log(test[0].tags["User Name"]);
Prosen Ghosh
  • 635
  • 7
  • 16
1

Little modification to what the variable should be like ... and if you wish to get the username of first tags :

var test = [{
    "id": "testtset",
    "name": "sf-rg",
    "tags": {
      "Tag Set": "005",
      "User Name": "Bond"
    },
    "properties": {
      "provisioningState": "Succeeded"
    }
  },
  {
    "id": "365tset",
    "name": "Test365",
    "location": "us",
    "properties": {
      "provisioningState": "Succeeded"
    }
  }
];


console.log(test[0]["tags"]["User Name"]);
ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
Exception_al
  • 1,049
  • 1
  • 11
  • 21
1

Your issue is not about the space in the key name, I am assuming you have made a typo pasting your json, and you are actually getting an array back:

var test = 
[
  {
    "id": "testtset",
    "name": "sf-rg",
    "tags": {
        "Tag Set": "005",
        "User Name": "Bond"
    },
    "properties": {
        "provisioningState": "Succeeded"
    }
  },
  {
    "id": "365tset",
    "name": "Test365",
    "location": "us",
    "properties": {
        "provisioningState": "Succeeded"
    }
  }
]

for the json above:

console.log(test[0].tags["User Name"]); should be fine

but

console.log(test[1].tags["User Name"]); will not be, as the second object has no tags property

paul
  • 21,653
  • 1
  • 53
  • 54