0

I have a JSON doc of the following format:

{
  "X": [
    {
      "a": "foo",
      "b": "bar"
    },
    {
      "a": "xyz",
      "b": "cvb"
    }
  ]
}

I need to pass this JSON object in my JS code and then need to fetch the value of "b" when I pass value of "a". Example: If I'm passing "foo" I want the output to be as "bar" and so on.

I'm writing this in MarkLogic so anyone who can help me with this?

James Coyle
  • 9,922
  • 1
  • 40
  • 48
Mehul
  • 148
  • 9
  • 1
    To be clear: The code you're going to use to access the value of `b` is going to be JavaScript, right? You've tagged [tag:javascript] and [tag:marklogic] says it supports JavaScript for queries, so I'm assuming so... – T.J. Crowder Feb 13 '19 at 11:06
  • Do you want to know how to get this in JavaScript? – Alias Feb 13 '19 at 11:06
  • 1
    @T.J.Crowder: Yes. – Mehul Feb 13 '19 at 11:08
  • @Alias: I thought of using "doc.toObject()" to convert it to a JavaScript object and then process it. – Mehul Feb 13 '19 at 11:08

1 Answers1

-1

I think you can do like this.

let obj = {
   x : [{
            "a":"foo",
            "b":"bar"
           },
           {
             "a":"xyz",
             "b":"cvb"
            }
          ]
  }
  
passValue = (value) => {
  
  obj.x.forEach(data => {
    // iterate through the keys 
    Object.keys(data).forEach(key => {
    // get the value for each key and look if required value has been matched
      if(data[key] == value){
        if(key == 'a'){
          console.log(data['b']);
        }else{
          console.log(data['a']);
        }
      }
    });
  });
}
<input type='button' onclick='passValue("foo")' value='pass value foo' />
<input type='button' onclick='passValue("bar")' value='pass value bar' />
<input type='button' onclick='passValue("xyz")' value='pass value xyz' />
<input type='button' onclick='passValue("cvb")' value='pass value cvb' />
noone
  • 6,168
  • 2
  • 42
  • 51