What is the process for pulling out a specific JSON element based on a condition?

I am working with a JSON object that looks like this:

  "links" : [ {
    "rel" : "first",
    "href" : "http://localhost:8080/first"
  }, {
    "rel" : "self",
    "href" : "http://localhost:8080/self"
  }, {
    "rel" : "next",
    "href" : "http://localhost:8080/next"
  }];

My goal is to retrieve the href URL where rel = "next". Question: how can I achieve this using JavaScript?

In Java, I would iterate through the array and create an inverted HashMap<Rel, Href>, then use map.get("next");.

But what is the equivalent method in JavaScript?

Answer №1

This solution is tailored for your needs.

var secured = {
    "connections": [{
        "relation": "start",
        "link": "http://localhost:8080/start"
    }, {
        "relation": "current",
        "link": "http://localhost:8080/current"
    }, {
        "relation": "upcoming",
        "link": "http://localhost:8080/upcoming"
    }]
};

var index,
    length = secured.connections.length;

for (index = 0; index < length; index += 1) {
    if (secured.connections[index].relation === 'upcoming') {
        console.log(secured.connections[index].link);
    }
}

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

Exploring the Power of React's Ref API

Currently, I am following tutorials on Udemy by Max where he discusses how to work with Ref Api's in React 16.3. In one of the lectures, he demonstrated creating a ref inside a container class, not App.js, using this.lastref = React.createRef();. He ...

Troubleshooting unexpected behavior with Custom Guest middleware in Nuxt Project

I have implemented the Nuxt auth module for my project. To manage the login page, I created a custom middleware called guest.js, which has the following code: export default function ({ $auth, store, redirect }) { if (!process.server) { if ($auth ...

Exploring a Ring with Three.js OrbitControls Rotation

I am having an issue with my OrbitControls camera setup. Currently, the camera rotates around a fixed point at player.position.x, y, and z coordinates. While it works fine, I need the camera to rotate around a ring instead. In the examples provided, the fi ...

ReactJS state not being updated due to a nested Axios call

Attempting to fetch data from nested axios calls, successfully retrieving responses from both calls. Struggling to update the prize_pool value within the second axios call. Any assistance would be greatly appreciated. getAllLeague() { axios.get(BA ...

Transform a dictionary into a personalized JSON object using C#

I've been mulling over this issue for hours now and I just can't seem to figure it out. I'm really hoping someone can point me in the right direction. The challenge I'm facing is converting a Dictionary object into a JSON format. Belo ...

Calculate the difference between the current value and the previous value

As I work on developing an app using vue.js, I am currently facing a minor issue. async fetchCovidDataByDay(){ const res = await fetch(`https://api.covid19api.com/live/country/${this.name}/status/confirmed`); const data = await res.json(); this ...

Utilizing encoding and decoding techniques in PHP and JavaScript with robust data attribute validation

I am utilizing data attributes to transfer information from HTML to JavaScript. The data attributes are derived from MySQL data, so they may contain spaces, resulting in validation errors since spaces are not permitted within attributes. My proposed solut ...

How can I use AngularJS orderBy to sort by a specific object's string property?

Is there a way to prioritize items in a task list based on both their date of addition and their listed priority? I've managed to sort the tasks by date, but I'm looking for a solution that will organize items with the 'HIGH' priority a ...

Experiencing the 'Rich Embed fields cannot be empty' error even though my code is functioning properly

My code is set up to log when someone edits a message on Discord. It captures the original message, the edited message, the channel, and more details. Everything seems to be working fine, but I keep encountering an error indicating that my RichEmbed fields ...

When the input value is changed programmatically, the onchange event does not execute as expected

Having trouble updating the content of my dataTable when using JS script to change the quantity value. Here is a snippet from my code. <h:inputText id="counterFeatures" value="#{myBean.quantity}"> <f:ajax event="change" render="myDataTable" ...

What is the best way to send an axios request in a Vue component to a route created by an Adonis controller?

My WidgetController.js file is responsible for handling CRUD operations on the database. Within this controller, there is a method/generator called * create (request, response) which returns widget attributes in a response and also inserts a new row into t ...

A guide on how to perform a PUT or DELETE operation for Azure Table Storage using Node.js

I've been faced with a challenge in my project where I aim to create basic CRUD functionality for Azure Table Storage. However, I'm encountering difficulties in generating a valid SharedKeyLite signature. While I can successfully generate valid ...

How can I use JavaScript api calls to retrieve an image url and insert it into an image tag in an

I have a JSON object that I need to use to retrieve images from a remote URL and display them in the img tag using API calls. The API link can be found at <div class="emoji"> <ul id="emojiz"></ul> <span style= ...

Converting child dictionaries with identical key names to CSV format using Python's DictWriter

Looking for a solution to format JSON files into CSV files? I have a specific structure in my json file, as shown below: [ {"A":{"value":1}, "B":{"value":2}}, {"A":{"value":9}, "B":{&quo ...

How to utilize JS variables for filtering an array in EJS?

Is there a way to filter my user array based on the "username" variable in JavaScript? On the server side: var users = data.filter(u => u.id.startsWith('user_')).map(u => u.value); // [{"username": "arin2115", "som ...

Converting a list of base classes to JSON using Unity's JSONUtility

I am working with a BaseClass and several subclasses. In my code, I have a List<BaseClass> that holds instances of these subclasses. When I try to convert this list to JSON using JSONUtility.ToJson(List<BaseClass>), it only includes propertie ...

Retrieving information through a jQuery ajax call

I've been working on creating an AJAX filter for a car list, but I've hit a roadblock in the final stage. My setup involves two files: index.php and filter.php. Within index.php, I have a form with dropdown lists and sliders. Here's the cod ...

What is the process for transferring ng-model values to a table in Angular?

My goal is to populate a table with JSON data using ng-repeat by clicking a button. I need to input either a first name or last name in order to display the results in the table. Is this the correct JavaScript function for achieving this? JavaScript Funct ...

Ways to modify the screen when a click event occurs

To make the display block when clicking this icon: <div class="index-navi-frame-box"> <p onclick="expandFunction()"> <i class="fa fa-bars"></i> </p> </div> Here is what it should change to: <div class=" ...

The bidirectional bindings within the component are malfunctioning

I just started learning Angular and I'm currently working on a small project. After following tutorials on two-way bindings, I attempted to implement it in my project. However, when I try to set values in the HTML for my component, it doesn't see ...