Retrieve information in JSON format from a document

I'm trying to extract data from a JSON file without knowing the exact location of the data. Here is an example JSON:

    var names= [
{
 "category":"category1" ,
     "name1":"david",
     "name2":"jhon",
     "name3":"peter"
},
{
 "category":"category2" ,
     "name1":"Smith" ,
     "name2":"Anna",
}
]

Let's say I have a string variable:

var str='category2';

How can I access the value of category2.name1 using the variable? I want to avoid hardcoding names[1].name1 and also steering clear of using a for loop.

Answer â„–1

If you need assistance, there are predefined functions that can be useful. For instance:

let filteredResults = items.filter(function(item, index, array) { 
  return item.type === target;
});

Your desired outcome will consistently appear in filteredResults[0].property when filteredResults.length > 0.

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

Add the file retrieved from Firestore to an array using JavaScript

Trying to push an array retrieved from firestore, but encountering issues where the array appears undefined. Here is the code snippet in question: const temp = []; const reference = firestore.collection("users").doc(user?.uid); firestore .collec ...

Utilizing Async/Await with an Unassigned Object

I'm facing a puzzling issue with an async/await function that refuses to assign to an object. Despite displaying the expected results in the console, when it comes to actually assigning to the object, it fails to do so. Let me elaborate below: Here&a ...

Troubleshooting: Issue with Chrome's CSV Export Functionality in JavaScript/AngularJS

Currently, I am troubleshooting an issue with exporting a CSV file from a data table on a web application. The export functionality works fine on all browsers except for Chrome when the export button is clicked. I have been trying to solve this problem for ...

Create a time of 00:19:59 using JavaScript

I am attempting to display a countdown timer that starts at 20 minutes in the format (00:20:00) using setInterval. Once the countdown is finished, it should display as (00:00:00), but I am having trouble achieving this. <body onload = "onloadFunc();" ...

Vue.js does not display HTML properly within the vue-swal component

I'm currently working on integrating HTML content into a Sweet Alert popup using this code snippet Link: https://www.npmjs.com/package/vue-swal this.$swal({ title: '<i>Custom HTML</i>', html:`This is an <em> em ...

Create a search feature based on names utilizing Node Express in conjunction with SQL database

After deciding to create an API with a search feature using SQL queries in node express, this is how I structured my code: app.get('/search/:query', (req, res) => { pool.getConnection((err, connection) => { if(err) throw err ...

Exploring the benefits of integrating Apache Thrift with TypeScript

After running the apache thrift compiler, I now have generated .js and .d.ts files. How do I incorporate these files into my current Angular2/Typescript project? I attempted to do so with the following lines of code: ///<reference path="./thrift.d.ts"/ ...

Unable to assign value to a public variable in Angular

I am facing an issue where I am trying to retrieve a value from the localStorage and assign it to a variable. However, when I try to use that variable in functions, it is coming up as undefined. code export class DashboardService { public token: any; ...

Default Selection Issue with Radio Buttons in AngularJS

I am currently encountering an issue with the code snippet included in my directive template '<li ng-repeat="f in foos">' + '<input type="radio" ng-change="foo(f.key)" ng-model="selectedFoo" name="foos" id="{{f.key}}" value="{{f.ke ...

"Discrepancy in results between JSON stringify and JavaScript object conversion

I need to save this object in a database, but first I have to send it to the backend. Recorder {config: Object, recording: false, callbacks: Object, context: AudioContext, node: ScriptProcessorNode…} However, after using JSON.stringify(recorder) The r ...

Monitoring AJAX POST progress with Node.js and Multipart: XMLHttpRequest

Is there a way to provide real-time updates on the size of a file being uploaded to a client, similar to how YouTube does it? I've looked into getting the full size of the file with req.files.myFile.size, but is there a method to track the current siz ...

NPM: There are no valid TypeScript file rules specified

Currently working on a small project using React.JS. Whenever I execute : npm run start, the following message gets logged: Starting type checking and linting service... Using 1 worker with 2048MB memory limit Watching: /Users/John/Projects/myProject/src ...

I'm seeing a message in the console that says "Form submission canceled because the form is not connected." Any idea why this is happening?

For the life of me, I can't figure out why this code refuses to run the handleSubmit function. Essentially, the form is supposed to take an input and execute the handleSubmit function upon submission. This function then makes a POST request to an API ...

Is there a way to extract only the titles from this JSON array? (using JavaScript/discord.js)

How can I extract the "title" values from this JSON array using JavaScript? I need to retrieve all the "title"s and store them in a new array like shown below: array( `hey title1`, `hey title2`, ... ) I am unsure of the number of titles we will receive, b ...

Transmit a data point from JavaScript to PHP

I am looking to transfer the address value to a different PHP page <script> var userAddress = place.formatted_address; document.getElementById('af').innerHTML = userAddress; </script> ...

Tips on extracting the image URL after uploading via Google Picker

I'm currently implementing the Google Drive File Picker on my website for file uploading. Everything seems to be working well, except I am facing an issue with retrieving the image URL for images uploaded through the picker. Below is my current JavaSc ...

What is the best method for converting a string picture URL into an image and showcasing it in an image tag?

I have a URL for an image that looks like this: C:\inetpub\MaujApp\OMSAPI\ManualReceivingImages\WhatsApp Image 2021-03-24 at 12.07.41 PM.jpeg My goal is to convert the original image and display it to the user using jQuery. I woul ...

Refresh ng-repeat array after implementing filter in controller

I am currently facing an issue with updating my table view when changing a variable that filters an array. The filter is applied in the controller based on the values of a specific variable called columnFilter. However, the filter does not reapply to updat ...

Eliminate the CSS triggered by a mouse click

Having some difficulty toggling the switch to change the background color. Struggling with removing the applied CSS and getting it to toggle between two different colored backgrounds. Code Sample: <!Doctype html> <html lang="en"> <head> ...

Javascript tabs with clickable links

I have created a page with a series of thumbnails that reveal content below when clicked. The content is positioned absolutely and set to display:none, with javascript changing this for each thumbnail. (I am not very familiar with javascript and learned t ...