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

Struggling to Upload a Json Array into Mongodb

How can I successfully import a jsonArray into a mongoDB using the Windows command prompt? The command I'm attempting to use is as follows: C:\mongo>mongoimport --jsonArray -d testdb -c testcollection -f my_test_file.json I have verified th ...

Tips for saving the status of an accordion controlled by an angular directive

I am currently utilizing the accordion directive from angular-bootstrap. My goal is to save the is-open attribute of this accordion, so that when users navigate to another page on the website, the state of the accordion (i.e. is-open) remains unchanged. ...

Optimizing resources by efficiently adding an event listener on socket.io

Recently, I've been delving into how JavaScript manages functions. Let's consider an example: io.on("connection", function(socket) { socket.on("hi", function(data) { socket.emit("emit", "hey") }) }) ...

Character count in textarea does not work properly when the page is first loaded

As English is not my first language, I apologize in advance for any grammar mistakes. I have implemented a JavaScript function to count the characters in a textarea. The code works perfectly - it displays the character limit reducing as you type. However, ...

Obtain the total number of result entries

I'm working on a project involving JS and PHP. My goal is to call a PHP file using Ajax and have it return the count of result lines. I use echo for this: $connection = new PDO($source, $user); $query = "SELECT * FROM scores WHERE username = '" ...

Eliminate duplicate items using the reduce method in JavaScript

Working with a set of Json Objects, I use a javascript map function to list each field along with an array of its possible types. For example: birthDate, [Date, String, String, String, String] isMarried, [Boolean, Boolean, Boolean, Boolean, String] name, ...

Using JSON JQ to filter data based on two conditions

Currently, I have the following setup which is functioning perfectly. However, I am looking to enhance it by adding an additional variable to the filtering process. Specifically, I would like to incorporate the "contains" method in order to filter based on ...

How can I utilize the JQuery GetJSON function to retrieve HTML content from an external webpage?

Imagine you're attempting a jQuery ajax request like this: $.ajax({ ... url: http://other-website.com ... }) You probably know that due to the same-origin policy, this request will fail because the URL is for an external domain. But the ...

Deriving variable function parameters as object or tuple type in TypeScript

Searching for a similar type structure: type ArgsType<F extends Function> = ... which translates to ArgsType<(n: number, s: string)=>void> will result in [number, string] or {n: number, s: string} Following one of the provided solu ...

Ember - Initiate a GET request to access a list of trees from an API endpoint

I have a project that utilizes Ember and Ember-Data with a requirement for a lazy-loaded tree-list. Within the API, there is an endpoint called /roots which contains children such as /roots/categories and /roots/components. These children are not fully lo ...

Exploring the possibilities of custom layouts for specific routes within the pages directory in Next.js

I am interested in incorporating layout-based routing within my project's pages directory. I want to find a way to have a specific file, like the _app.tsx, that can only affect the files located inside a particular folder. This setup would operate si ...

Tips for organizing JSON data from Google Maps' Direction Service for storage in a MongoDB database and displaying it on a map

Utilizing the Google Maps Directions service for navigation, I aim to preserve the response in MongoDB in JSON format. This will allow me to easily plot the route on the map again. How should I structure the JSON data for the routes array retrieved from th ...

Are none of the page links clickable?

Currently, I am in the process of creating a portfolio website. This is my first attempt at coding HTML and CSS from scratch without the aid of a layout template. I've encountered an issue that has me stumped - the links within the container are not ...

Stop the form submission until validation is complete

I'm currently working on a form and encountering some validation issues. HTML: <form id="regForm" class="form-group" method="POST" action="signup.php"> <div class="col-md-12"> <h2>Job Pocket</h2> </div> <di ...

I'm curious as to why IPC messages from one menu item in Electron can successfully reach my window, but when sent from a different menu item, they do not seem to

I am working on a straightforward application that requires running a background process to fetch some data. I want to display a loading indicator while the data is being retrieved, but I am encountering difficulties implementing this feature. My approach ...

Are JSON structures safe to use with advanced constructs like functions, the new keyword, and function calls?

Utilizing JSON is an effective method for transferring intricate data from the server side to client side JavaScript. For instance, in languages like PHP, a simple code snippet can achieve this: <script type="text/javascript> var MyComplexVariab ...

Navigating the reactive array in Vue 3 with finesse

Currently, I'm facing some challenges with my Vue 3 app in terms of getting things to work as expected. The main issue lies in properly accessing a reactive array. Let me provide you with the code for better comprehension: Within my global store sto ...

What is the method to ensure an element is displayed in Selenium WebDriver?

Looking for assistance on how to choose options from a dropdown when the element is not visible and has a boolean attribute? Here's the HTML code snippet: <select id="visualizationId" style="width: 120px; display: none;" name="visualization"> & ...

Create a duplicate of array A in JavaScript with the keys transferred to array B, then make modifications to the elements in

Currently, I am delving into JavaScript in regards to array assignment and cloning. A puzzling issue arises when attempting to clone the elements of array A into array B using the spread operator "...". Surprisingly, when modifying the elements in array B, ...

Learn the process of dynamically loading scripts and their functions in Angular

At first, I had the following code statically placed in Index.html and it was functional. <script src="/le.min.js"></script> <script> LE.init({ token: 'token', region: 'x' }); </script> ...