How can you extract a JSON object from a JSON array based on a key that is associated with a specific JSON

Is it possible to retrieve a specific JSON object from an array of JSON objects based on a condition?

[
{ id: 1, name: "larry" },    
{ id: 2, name: "curly" },
{ id: 3, name: "moe" }
]

For example, if I want to extract the object where name is equal to "larry", can this be done?

{ id: 1, name: "larry" } 

If you have any insights or solutions, please share them.

Answer №1

Learn how to utilize jquery $.grep() for searching within JSON data.

var jsonData = [
  { id: 1, name: "larry" },    
  { id: 2, name: "curly" },
  { id: 3, name: "moe" }
];

var data= $.grep(jsonData, function(element, index){
  return element.name == 'larry';
});

console.log(data[0].id+ "====" + data[0].name);

Answer №2

It seems like I understand your question, but would this code be what you're looking for?

let myData = jsonObj[0];

console.log(myData.id + " " + myData.name);

Alternatively, if you want to search by name:

let myData;

for (let j = 0; j < jsonObj.length; j++){
  // find the object with a matching name
  if (obj[j].name === "larry"){
     // match found
     myData = obj[j];
  }
}

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

The Ajax request yields a response consisting of an array filled with blank objects

Currently, I am utilizing PHP object-oriented programming to fetch data from the database. The data is retrieved successfully, but when I attempt to make AJAX calls, it returns an array of empty objects. How can I ensure that the objects return the actual ...

Can you explain the distinction between submitting a form through the ajax() method versus using <form action="xyz" method="POST"> to communicate with a servlet or PHP script?

Currently, I am exploring jQuery Mobile and implementing a basic form submission to a servlet using a straightforward method. However, after some research on Google, I discovered that most developers are opting for the Ajax method instead. I'm curious ...

Looking for guidance on organizing and editing a JSON payload in Java?

Displayed here is a simplified JSON payload that requires some modifications (the original version is longer). { "request": { "jsonRequest": { "Alpha": { "Bravo": [ { "D ...

"Troubleshooting: Vue JS Axios Post Request Not Passing Data to PHP Server

After successfully uploading an image in Vue JS and sending a POST request to a Laravel Route, the JSON response from the API is displayed on the client side as expected. However, there seems to be an issue with retrieving this response in PHP, as it retur ...

Dropdown menu utilizing processing API and interacting with AJAX and DOM manipulation

My API data is not showing up in the dropdown menu. If I use ?act=showprovince, I can see the result. example.html <head> <link rel="stylesheet" type="text/css" href="css/normalize.css"> <link rel="stylesheet" type="text/css" hr ...

How can you customize your WooCommerce add to cart functionality using Ajax to set a unique price for your products?

My current challenge involves adding a product to the cart during checkout through an on_click event. The price of this product is calculated dynamically using an external API, causing it to register with a price of 0 in WooCommerce itself. While I have su ...

What causes an Undefined array key error when using AJAX POST?

I am having trouble passing a text string to a PHP Variable using AJAX. Every time the POST request is sent, I see this error message: Warning: Undefined array key "mydata" Although the alert displays the correct value, the PHP page shows the ...

Animation will cease once the page is refreshed via Ajax

I'm facing a challenge with a problem that I can't seem to resolve. The issue lies in my use of this plugin for displaying random images. The only step left is to refresh the content within the div. However, every time I attempt to do so, the an ...

When scrolling, use the .scrollTop() function which includes a conditional statement that

As a newcomer to jQuery, I've been making progress but have hit a roadblock with this code: $(window).scroll(function(){ var $header = $('#header'); var $st = $(this).scrollTop(); console.log($st); if ($st < 250) { ...

Having issues with Angular when dealing with loading a div through the jQuery load function

I am facing an issue with my master page that includes a script for angularJs and a div serving as a parent div to load an html page developed using Angular. MainPage.aspx <script src="../../Scripts/angular.min.js" type="text/javascript"></scrip ...

Is it possible to establish a scope for jquery.ajaxSetup()?

Currently, I am working on a project involving numerous ajax calls with repetitive parameters. After some consideration, I am contemplating using jquery.ajaxSetup() to streamline the code. However, jQuery does not recommend this approach in their API docu ...

Retrieve information from a PHP file using AJAX when the output is just a single line

I never thought I would find myself in this situation, but here I am, stuck. I just need a single result from this PHP file, so is using an array really necessary? Despite my efforts to console.log(result) multiple times, all I get back is "null". What c ...

What is the best way to toggle the visibility of a progress bar for PageMethods?

As I work on developing a web application with asp.net framework 4.0, I have incorporated multiple PageMethods to ensure complete AJAX functionality without using UpdatePanel for partial postback. However, the challenge arises when I need to display a prog ...

Retrieve the unique identifier of a single post from a JSON file within a NuxtJS project

Is there a way to retrieve the unique post id data from a JSON file in NuxtJS? created() { this.fetchProductData() }, methods: { fetchProductData() { const vueInstance = this this.$axios .get(`/json/products.json`) ...

Creating a multi-level JSON object from a string: A step-by-step guide

I've organized my HTML file in the following structure: Chapter 1.1 1.1.1 interesting paragraph 1.1.1.1 interesting paragraph Chapter 1.2 1.2.1 interesting paragraph 1.2.1.1 interesting paragraph ... Chapter 11.4 ... 11.4.12 interesting ...

Upon successful completion of the Ajax call, refresh the page without causing any blinking

Hey there, I'm facing an issue with my website, I've implemented ajax to fetch data from my API, and upon successful retrieval, I need to reload the page to display the information, However, sometimes the page blinks before reloading, while oth ...

A guide on efficiently incorporating a php variable into json format, then transferring it to ajax

My Sample Code var ajaxResponse = xmlhttp.responseText; //ajax response from my php file jsonData = JSON.parse(ajaxResponse); alert(jsonData.result); And in my PHP Script $resultValue = 'Hello'; echo '{ "result":"' . $result ...

Error encountered while attempting to parse text using JSON

Greetings! I have encountered a JSON object that appears like this: {"messages":["operator will assist you"]} However, when I attempt to parse it using $.parseJSON(json), an unexpected character error occurs, specifically SyntaxError: JSON.parse: unexpec ...

Storing arrays as JSON in PostgreSQL

Hey there, I'm struggling with a json array issue in postgresql. Here's the query that's causing me trouble: select array_to_json(array_agg(row_to_json(t))) from ( select id, ids, liv, tip, ide, idf nome, ico, rgb, ( select arr ...

issue with eval() function

I am attempting to convert a JSON string from my .php file using the eval() function, but it is not working. The browser console shows a SyntaxError: expected expression, got '<'... However, when I comment out the line where eval() is used an ...