Tips for extracting JSON data from an API with identical names as values

I am working on a project to create a data search system using JSON. The JSON data is stored in a REST API, and the structure of the API is as follows:

[
    {
    "info": "cute but big animal",
    "type": "pig",
    "name": "patty"
    },
    {
    "info": "Barks all the time",
    "type": "dog",
    "name": "parker"
    },
    {
    "info": "Makes delicious eggs",
    "type": "chicken",
    "name": "chicky"
    }
]

There are multiple values with the same name in the data.

After doing some research, I found various suggestions online mentioning the use of indexing to retrieve specific data like data.value[1].

My goal is to be able to search for "patty" and retrieve the corresponding info and type fields directly from the JSON data without indexing.

I will be implementing this functionality using JavaScript or Node.js.

Answer №1

If you happen to have both the key and value at hand, it appears that this is the most straightforward method:

const arrayOfObjects = [
    {
    "info": "cute but big animal",
    "type": "pig",
    "name": "patty"
    },
    {
    "info": "Barks all the time",
    "type": "dog",
    "name": "parker"
    },
    {
    "info": "Makes delicious eggs",
    "type": "chicken",
    "name": "chicky"
    }
];

const key = 'name';
const value = 'patty';
const object = arrayOfObjects.find(obj => obj[key] === value);

console.log(object);

If you are unsure of the key, here's an alternative approach:

const arrayOfObjects = [
    {
    "info": "cute but big animal",
    "type": "pig",
    "name": "patty"
    },
    {
    "info": "Barks all the time",
    "type": "dog",
    "name": "parker"
    },
    {
    "info": "Makes delicious eggs",
    "type": "chicken",
    "name": "chicky"
    }
];

const value = 'patty';
const object = arrayOfObjects.find(
  obj => Object.values(obj).some(val => val === value)
);

console.log(object);

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

Explore the JSON file to locate a legitimate IP address and extract it

I'm trying to extract an IP address from a JSON file I have received. Is it possible to simply remove everything else and grab the IP address directly? What would be the most effective method for extracting this string? Code: if data['secret&ap ...

Utilizing CSS-in-JS to eliminate arrow buttons from a TextField

I'm currently developing a webpage using React and Material-UI. One of the components I have is a TextField element, and I need to remove the arrow buttons that typically appear on number input fields. If I were utilizing CSS, I could easily achieve t ...

Deciphering JSON data with Go

This JSON output example demonstrates the result of calling 'ListObjects' for AWS S3 { "Contents": [{ "ETag": "9e2bc2894b23742b7bb688c646c6fee9", "Key": "DSC-0237.jpg", "LastModified": "2017-09-06 21:53:15 +0000 UTC", ...

formik does not support using the "new Date" function as an initial value

I have been trying to set the initial value of a date in my component like this, but when it renders I am encountering an error. const formik = useFormik ({ initialValues: { dob: new Date () } }) During this process, I'm facing the follow ...

The useEffect alert is triggered before the component is re-rendered

Can someone help me understand why the HP in the code below is displayed as "1" when the alert is thrown, and only set to "0" after I confirm the alert? Shouldn't the component be rerendered before the alert is thrown so that it has already been displ ...

Angular 8: How to Retrieve Query Parameters from Request URL

Can I retrieve the GET URL Query String Parameters from a specific URL using my Angular Service? For example, let's say I have a URL = "http:localhost/?id=123&name=abc"; or URL = ""; // in my service.ts public myFunction(): Observale<any> ...

The sequence of data and the final event triggered by http.createServer

const server = http.createServer(async (request, response) => { if (request.method === "POST") { var data = ""; request .on("data", async (chunk) => { console.log("1"); data + ...

Unable to perform updates for personalized fonts

I've been trying to incorporate custom fonts into my website, but I seem to be facing difficulties in actually implementing them. Could someone please let me know if I am doing it correctly? .pattern{ background:rgba(0,0,0,.5) url(../images/pattern ...

AngularJS modal behaving oddly when checkboxes are used

My Angular app is available in this plunker. Upon clicking the button, a modal dialog opens displaying a list of items. Two of these items are pre-checked based on conditions set in the checkbox table input. The following function handles pushing and spl ...

Having trouble extracting JSON from the HTTP response?

Currently, I'm struggling to find a solution in order to properly extract and process the JSON data from . While my code has no issues decoding the JSON data retrieved from , it always returns empty or zero values when directed towards the CoinMarketC ...

Error encountered: npm could not create a directory due to an unknown issue

After running the command npm install && npm run dev, I encountered an error message: npm ERR! code UNKNOWN npm ERR! syscall mkdir npm ERR! path C:\Users\user\AppData\Roaming\npm-cache\_cacache\content-v2\sha ...

Decoding JSON using abbreviated keys in C#

I am in the process of transferring a project from Android to Windows Phone 8 and am struggling to find information on how to specify which JSON key corresponds to each object field. In my Android code, I utilized Google GSON and the SerializedName annota ...

Is there a way to convert datetime format to date in a Vue component?

With my Vue component set up like this: <template> ... <td>{{getDate(item.created_at)}}</td> ... </template> <script> export default { ... methods: { getDate(datetime) { ...

Tips for sending a JavaScript variable through an AJAX URL

I currently have a variable defined like this: var myip; I need to include this variable in the following URL: $.ajax('http://api.ipstack.com/**[myip]**?access_key=mykey') Manually replacing [myip] with my IP address works fine, but I am loo ...

The Selenium driver's execute_script method yields no result

One of the tasks I have is to determine if a specific element is within view. If it is, I want the script to return True; otherwise, False: driver.execute_script('window.pageYOffset + document.querySelector(arguments[0]).getBoundingClientRect().bottom ...

Send a parameter to an Angular directive when clicked

I am working on a directive that will allow me to retrieve parameters upon clicking. I need to access the child data within the click event to determine if it has children or not. ..... html div ng-app="treeApp"> <ul> <treeparent>< ...

Having trouble locating the correct JSON array syntax for Highcharts

Hey there! I'm currently facing a bit of a challenge while trying to set up a JSON array using PHP and integrate it into Highcharts. Currently, I am creating the array in this manner: $stack[] = array($commname => $countit); $stack = json_encode( ...

Ways to conceal numerous objects

I need to create a function where I can hide multiple elements by pressing a button based on the value of checkboxes. If a checkbox is checked, the corresponding element should be hidden. Currently, I have some code that only works for the first element: ...

Is the Okta SDK compatible with all identity providers?

I am looking to incorporate a wide range of Identity providers into my app, such as Auth0 SSO OIDC, Onelogin SSO OIDC, Google SSO OIDC, and others. Is it possible to use this solution to make that happen? https://github.com/okta/okta-auth-js ...

Express.js automatically sets timeouts for requests to static files

I've been facing this issue for several weeks now - after launching, Express functions properly for a few hours and then suddenly stops serving static files. The situation is as follows: GET / 304 153ms GET /js/bootstrap.min.js 200 120000ms GET /img/ ...