1

I have a 2 arrays that look like this:

vars arrayVars = ["s", "p", "o"]

arrayBindings = [     {
        "s": { "type": "uri" , "value": "http://ss.ldm.io/" } ,
        "p": { "type": "uri" , "value": "http://xmlns.com/foaf/0.1/name" } ,
        "o": { "type": "literal" , "value": "ss" }
      } ,
      {
        "s": { "type": "uri" , "value": "http://ss.ldm.io/" } ,
        "p": { "type": "uri" , "value": "http://xmlns.com/foaf/0.1/img" } ,
        "o": { "type": "uri" , "value": "http://fbcdn-sphotos-d-a.akamaihd.net/o.jpg" }
      },
      ...
      ]

I want to be able to navigate the arrayBindings dynamically based on the parameter of the first one, basically:

arrayBindings[0].s.value gets me "http://ss.ldm.io/" but doing it in way like arrayBindings[0].arrayVars[0].value which deosn't work.

2 Answers 2

1

That's where the [] notation comes in handy:

arrayBindings[0][arrayVars[0]].value

var arrayVars = ["s", "p", "o"]

var arrayBindings = [     {
        "s": { "type": "uri" , "value": "http://ss.ldm.io/" } ,
        "p": { "type": "uri" , "value": "http://xmlns.com/foaf/0.1/name" } ,
        "o": { "type": "literal" , "value": "ss" }
      } ,
      {
        "s": { "type": "uri" , "value": "http://ss.ldm.io/" } ,
        "p": { "type": "uri" , "value": "http://xmlns.com/foaf/0.1/img" } ,
        "o": { "type": "uri" , "value": "http://fbcdn-sphotos-d-a.akamaihd.net/o.jpg" }
      },
]
                     
document.write(arrayBindings[0][arrayVars[0]].value);

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

Comments

0

You can access object properties by using brakets ([]) or dot (.) notations:

Thus, arrayBindings[0].s.value and arrayBindings[0]['s']['value'] return the same value http://ss.ldm.io/

Read this

Now, looping over your two arrays, dynamically :

for (i = 0; i < arrayBindings.length; i++) {
    for (j = 0; j < arrayVars.length; j++) {
        document.write(arrayBindings[i][arrayVars[j]].value);
    }
}

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.