Getting information from a JSON key:value pair can be done easily using JavaScript

My JSON document is structured as follows:

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

I have a requirement to retrieve the value of "b" based on the input of "a" in my JavaScript code. For example, if I provide "foo" as input, I should get "bar" as output.

Since I am working with MarkLogic, I am seeking assistance from anyone familiar with this for guidance.

Answer №1

If you're wondering how to accomplish this task, here's one way to go about it:

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' />

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtain the rotated coordinates for the top and left positions

I am trying to determine the rotation of a specific point in terms of its top and left positions. It's proving to be quite complex as it involves knowing the original top and left coordinates, applying scaling, and then calculating the rotation. Curr ...

What is the best way to convert an IEnumerable<DateOnly> into a serializable format?

I created a personalized JsonConverter to serialize the DateOnly data type, however I am unsure about how to utilize this converter with a collection such as IEnumerable. ...

The SSR React application rendering process and asynchronous code execution

When using SSR with React, how is the content that will be sent to the client constructed? Is there a waiting period for async actions to finish? Does it wait for the state of all components in the tree to stabilize in some way? Will it pause for async ...

Issue: EROFS error encountered when trying to read 'metadata.json' as the file system is read-only. I utilized Firebase Functions to deploy the json file, but am unable to make any changes to it

I've encountered an error while using firebase functions. Can someone please check this and provide me with a solution? Error: EROFS: read-only file system, open 'metadata.json' at Object.openSync (fs.js:498:3) at Objec ...

Rails application encounters issue where CKEditor is removing style elements from span classes

In my current setup using Rails 4.1.4, Ruby 2.1.2, and CKEditor 4.1.1 integrated with Rails Admin, I am facing an issue. Whenever I enter text in the CKEditor text area and apply a font or font size, it saves successfully. However, upon viewing the content ...

Unable to adjust metadata titles while utilizing the 'use client' function in Next.js

I have a /demo route in my Next.js 13 application, and it is using the App Router. However, I am facing an issue with changing the title of the page (currently displaying as localhost:3000/demo). The code snippet for this issue is shown below: /demo/page ...

Having trouble interpreting JSON responses in AngularJS

How do I access the "teams" array from this JSON response using AngularJS? { "_links" : { "search" : { "href" : "http://localhost:8080/teams/search" } }, "_embedded" : { "teams" : [ { "name" : "Perspolis", "location" : ...

Acquiring images from an external source and storing them in either the $lib directory or the static folder during the

Currently, I have a Sveltekit project set up with adapter-static. The content for my pages is being pulled from Directus, and my images are hosted in S3, connected to Directus for easy access. I am also managing audio samples in a similar manner. During b ...

When a dropdown replaces the value of another

I'm currently working on a page using JavaScript, React, and Formik. I have encountered an issue with two dropdowns within one form - when I select a value in one dropdown, the value in the other resets. To illustrate this problem, I have included a g ...

Creating high-quality tabs for a gaming project

I tried following a tutorial on YouTube to create some professional tabs, but unfortunately my code didn't turn out the way I wanted. I was hoping to be able to scroll through different tabs and have a separate HTML file for each one. Although I&apos ...

Serializing a single object in Django

res = {'name':'man','surname':'seal'} encoded = json.dumps(res) return render_to_response('example.html',{'encoded':encoded} ) example.html {{ encoded }} I am experiencing success with this cod ...

"Displaying slider position relative to total count before clicking on it for

Utilizing the Foundation Zurb 6/Orbit Slider. Is there a way to show the current slide count and total before the slidechange.zf.orbit event triggers? Should I integrate an event prior to this, on window load, or use another method? The first slide initi ...

Dealing with an unexpected token error in JSON when faced with two lines

When downloading content from the server into a file and dealing with multiple lines of JSON, an unexpected token error occurs due to new line characters. How can this issue be resolved? Data from the server {"level":"info","message":"Test Log messages" ...

Combine words into lowercase in JavaScript variable

I'm struggling to understand why the data from a form field input is not being stored correctly in a SharePoint column data collection. Currently, when someone inputs a name into a form field, it should automatically populate a SharePoint list: http ...

What could be causing these errors to occur when I use the fetch API?

Having trouble fetching the news API and getting this error message: TypeError: Cannot read properties of undefined (reading 'map'). Any suggestions on fixing this issue? Your help is much appreciated. import React, { Component } from 're ...

jQuery - Navbar with both horizontal and vertical orientation

I'm new to JavaScript and jQuery, and I'm looking to create a vertical nav/slider that follows the cursor when hovering over horizontal navbars links to reveal sub-links, essentially creating a dropdown menu effect. While I don't expect any ...

PHP - Combining and removing duplicate inner arrays in a multidimensional array

Initial Array: Array ( [0] => Array ( [0] => "Kate" [1] => Array ( [0] => 1 [1] => 30 [2] => 11 ) [2] => "Seattle" ) [1] => Array ( [0] => "Kate" [1] => Array ( [0] ...

What is the reason for the absence of the Express property "ip" in the list generated by

Check out this code snippet: const express = require('express'); const app = express(); app.get('/', function(request, response) { console.log(Object.keys(request)); console.log(request.ip); }); app.listen(1337); The first log ...

Is there a more efficient method for implementing server side rendering in a Next.js application?

Currently, I am implementing server-side rendering in my Next.js application. This specific component is responsible for returning HTML content. I'm wondering if there are more efficient methods available? import Feature from 'components/home/Fea ...

How to properly format credit card input using JavaScript or jQuery

I need to implement a feature where users input their credit card information, and once they complete the form, I want to display the credit card number in this format: xxxxxxxxxxxx1111 or xxxx-xxxx-xxxx-1111, without altering the actual input value. Is ...