Postman's ability to capture elements that meet specific criteria set by another element

Here is the output of my response code:

[
    {
        "id": 364,
        "siteName": "FX21 - PortA",
    },
    {
        "id": 364,
        "siteName": "FX21 - PortB",
    },
    {
        "id": 370,
        "siteName": "FX05 - ER",
    },

I'm trying to extract siteName values where id equals 364 and store them in an array variable using Postman. The expected array should be [FX21 - PortA, FX21 - PortB]

However, the code I've attempted so far only retrieves the first siteName value:

var requiredId = pm.response.json().find(function(element){
    if (element.id == "364"){

        return element;
    }
});

Answer №1

  • Utilize Array.filter along with a filter for the value 364 in the id property.
  • Then, employ Array.map to transform the filtered results into an array containing only the siteName values.
  • Additionally, use destructuring assignment to extract the keys of the object:

const response = [
    {
        "id": 364,
        "siteName": "FX21 - PortA",
    },
    {
        "id": 364,
        "siteName": "FX21 - PortB",
    },
    {
        "id": 370,
        "siteName": "FX05 - ER",
    }
]
function getSiteNameById(idFilter){
 return response.filter(({id}) => id === idFilter).map(({siteName}) => siteName);
}
console.log(getSiteNameById(364));

Alternatively, you can utilize Array.reduce to accomplish this task in one step by checking for the id and accumulating the elements in the final array:

const response = [
        {
            "id": 364,
            "siteName": "FX21 - PortA",
        },
        {
            "id": 364,
            "siteName": "FX21 - PortB",
        },
        {
            "id": 370,
            "siteName": "FX05 - ER",
        }
    ]
function getSiteNameById(idFilter){
 return response.reduce((acc, ele) => {
    return  ele.id === idFilter ? acc.concat(ele.siteName) : acc;
 }, []);
}
console.log(getSiteNameById(364));

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

A sleek and streamlined scrollspy that dynamically updates the active class exclusively for anchor tags

Can anyone help me with this coding problem? I'm currently working on a minimalistic scrollspy code that adds an active class when the content is offset.top. The code works fine, but I want to change the active class to apply to the "a" tag instead of ...

When attempting to select an option from the dropdown menu, I encounter an issue where the

My code is not behaving as expected. Whenever I click on the child elements, the dropdown changes to display: none. I am encountering an error when clicking on the input frame and displaying:none. How can I resolve this issue? I would like to be able to ...

Having trouble with clearTimeout and clearInterval functions not functioning properly?

Currently, I've set up a countdown using both setInterval and setTimeout functionalities, and it seems to be running smoothly. However, I encounter an issue when trying to stop the countdown upon clicking a certain button; it pauses only after complet ...

Unraveling Loops in Data Structures through Two-Step Deserialization

I am currently working with a Serializer/Deserializer that utilizes the PreserveReferencesHandling = PreserveReferencesHandling.All property. The challenge I am facing revolves around circular references within my code. Allow me to provide a simple examp ...

Using PHP to upload images through AJAX increases efficiency

Worked tirelessly on this script all night still unable to fix the bug. The issue is that when I select an image and click upload, it uploads the current image file. Then, if I select another image and click upload, it uploads two new files along with the ...

In the Rails environment, it is important to verify that the data sent through $.post method in jQuery is correctly

I’m facing an issue with my jQuery script when trying to post data as shown below: $.post({ $('div#location_select').data('cities-path'), { location_string: $('input#city_name').val() }, }); Although this code work ...

What is the best way to determine if a radio button has been chosen, and proceed to the next radio button to display varied information?

The goal is to display the <div class="resp"> below each radio button when it is selected, with different content in each <div class="resp">. The previously selected <div class="resp"> should be hidden when a new radio button is chosen. O ...

Exploring the data connections in Firebase Realtime Database using angularfire2

I am in need of querying comments and only requesting users that are listed in the comment by their userId. This is the structure of my database in Firebase realtime db: { "comments" : { "c_id1" : { "commentId" : "c_id1", "commentText" ...

Transform JSON data into a Google Sheet using Google Apps Script

Having trouble inserting the JSON response into Google Sheet using Google Apps Script with the code below. Running into errors, even though I can't seem to pinpoint the issue. Take a look at the screenshot and code snippet provided: function myF ...

Is there a workaround for utilizing a custom hook within the useEffect function?

I have a custom hook named Api that handles fetching data from my API and managing auth tokens. In my Main app, there are various ways the state variable "postId" can be updated. Whenever it changes, I want the Api to fetch new content for that specific p ...

Encountering a bad request error while attempting to update a numeric value in MongoDB

I attempted to update a single element in mongodb, specifically a number value. Below is the request sent to the DB: const handleDelivered = (num) =>{ const total = service.quantity; const final = parseInt(total) + num; console.log(tota ...

Unable to precisely reach the very bottom of the scrollbar

When trying to move to the bottom of the scrollbar, I seem to reach a bit higher than the actual bottom. https://i.stack.imgur.com/Vt83t.png Here is my code: ws.onmessage = function (event) { var log = document.getElementById('log') ...

Tips for retrieving information from a dynamically created form using VUE?

Welcome Community I am working on a parent component that includes a child component. The child component dynamically renders a form with various controls from a JSON object retrieved via a Get request using Axios. My goal is to be able to read and loop ...

I'm looking for a way to set up a PropType that accepts a boolean value, but also allows for

Currently, my code includes a Modal component with a prop called disableEscapeKeyDown. The PropType defines it as boolean | null, but when trying to use it in the ModalWindow function, I receive an error stating Type 'boolean | null' is not assig ...

Encountered SyntaxError: An unexpected token has been found while integrating leaflet with flask

Despite adding all necessary scripts and configuring my API_KEY in config.js, I keep getting an error message saying "Uncaught SyntaxError: Unexpected token." I have double-checked my API key multiple times, and it seems to be correct. Here is a snippet f ...

The contents of a Javascript array are not appearing within a div element

I have developed a program that reads JSON data related to a concert event. The JSON file consists of an object named global, which includes details about the band name and venue. Additionally, there is a tickets object that contains information on all ava ...

"Exploring the world of JSON with Android and Java

Just delving into the world of JSON and experimenting with the FLOT graph for displaying graphs via WebView. Struggling with JSON parsing to represent my data as JavaScript expects. Despite hours of tinkering, I can't seem to format my JSON output to ...

Unexplained Reference Error in Next.js Typescript: Variable Accessed before Initialization

I am currently working on an admin website and encountered the error Block-scoped variable used before its declaration.. I will provide details using images and code. This is my first time seeking help on StackOverflow. Error Message: Block-scoped variab ...

do not continue loop if promise is rejected in AngularJS

I've attempted multiple methods, but still haven't found a solution to this issue. Within my code, there is a method called iterator that returns a promise; this method runs in a loop x number of times. If the iterator function returns a rejecte ...

When using Jquery, hovering over an element will cause the full title to be

I have created a toggle div that displays an ellipsis (...) when the long title is longer than 30 characters. Now, I want the full text of the long title to appear when hovering over the div. Check out this JS Fiddle for reference. JS $('#popu ...