Simplest Method to Retrieve a Boolean Value for a Searched Pair of Key/Value (JavaScript)

My task involves working with a JSON string that looks like this...

JSON:

[{"my_id":"100002","my_confirmation":"682354682"},{"my_id":"100005","my_confirmation":"281735345"},{"my_id":"100009","my_confirmation":"361567356"}]

After parsing this JSON into a key/value pair array, I need to figure out the simplest way to use JavaScript to return a boolean value when trying to find a match for "my_id" with the value of "100005". And is it necessary to first parse the JSON into an array?

Answer №1

When working with JSON strings in ECMA5, you can utilize Array.prototype.some to parse the data.

Here is an example in Javascript:

var jsonString = '[{"my_id":"100002","my_confirmation":"682354682"},{"my_id":"100005","my_confirmation":"281735345"},{"my_id":"100009","my_confirmation":"361567356"}]';

var matches = JSON.parse(jsonString).some(function (obj) {
    return obj.my_id === '100005';
});

console.log(matches);

This code will output:

function myContains(jsonStr, key, value) {
    return JSON.parse(jsonStr).some(function (obj) {
        return obj[key] === value;
    });
}

var jsonString = '[{"my_id":"100002","my_confirmation":"682354682"},{"my_id":"100005","my_confirmation":"281735345"},{"my_id":"100009","my_confirmation":"361567356"}]';

console.log(myContains(jsonString, 'my_id', '100005'));

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

Discover the secrets of extracting the ID from a MenuItem within a Menu

Table Ui with menu Struggling with fetching the correct user ID in the edit button The edit button for all users is only displaying the last user's ID If the edit button is not nested inside the Menu, it works fine. However, within the Menu, it onl ...

Generating JSON data from Dom elements within a specified `div` container

My goal is to extract all the elements from within a div element, which may consist of multiple inputs, checkboxes, radiobuttons etc. After that, I want to convert the id or name and value attributes into a format that can be read as JSON. I attempted to ...

Loop through each item in order to modify the text within the pop-up using a for loop

Goal Upon clicking a .player, a popup should display with relevant data about that player fetched from players.js Issue: When clicking on a player, the event seems to trigger multiple times instead of just once. This results in retrievi ...

Understanding the binary format in JavaScript

In my JavaScript project, I am facing a challenge with reading a large table that contains a mix of numbers, enums, and strings. The data is significant in size, so I am exploring the option of converting it to binary format to save space. However, I' ...

Calculating the disparity between two dates using a predetermined format

const calculateChatDateFormat = (chatDate) => { // round to the nearest whole number const dt = Moment(chatDate).format('MMMM Do YYYY, h:mm:ss a'); // March 9th 2021, 7:16:16 pm; const dtNow = Moment(new Date()).format('MMMM D ...

Restrict OrbitControls to a specific region of the page that is separate from the rendering area

As an experienced COBOL programmer delving into the world of Javascript and Three.js for a personal project, I've been grappling with a particular question for the past couple of days. Despite scouring StackOverflow for answers related to OrbitControl ...

md-list-item containing md-radio-button

Trying to tackle this particular issue: https://github.com/angular/material2/issues/1518 I want the ability to click anywhere on the line of my md-item and have it trigger the radio-button action. settings.component.html : <md-radio-group [(ngModel) ...

The importance of displaying doughnut chart tooltips in Angular 5 console

Is there a way to consistently display tooltips for a doughnut chart? This code snippet might help: Chart.pluginService.register({ beforeRender: function(chart) { if (chart.config.options.showAllTooltips) { // create an array of tooltips // we ...

Retrieve the final element of an array by utilizing JSON parsing through Neo4j's APOC extension

Task description: I am in need of extracting the last element from the "xpath" fields within a nested JSON array/list. Below is an example of the input JSON data: { "origin": [{ "label": "Alcohol drinks", "tag": [], ...

Having difficulty consolidating the data received from the Twilio API

My goal is to retrieve billing data from the Twilio API and store the fetched value in a variable for display on my web application. Despite my attempts with async and await, I've encountered difficulties getting it to function as intended. const twil ...

The functionality of using regular expressions in a Mongoose `find` query seems

I am attempting to create a select query in MongoDB using Mongoose like this: SQL SELECT * FROM PRODUCTS WHERE NAME LIKE '%Sorv%'; Here is my Product model: mongoose.model('Products' , new mongoose.Schema({ name: {typ ...

Utilize JSON data to dynamically populate TextFields or Select menus depending on a specific key in the JSON object

As I retrieve multiple JSON groups from an API, each group contains one or more questions objects. The task at hand is to attach each question along with its corresponding response to a textField. Based on the value of QuestionType, it will be decided whet ...

What is the best approach for handling AJAX requests using JSON in Web Forms?

While MVC controllers are known for serving JSON formatted AJAX requests efficiently, I'm curious if ASP.NET offers any built-in functionality that can handle these types of calls in a traditional web forms site. ...

Displaying a binary PDF file in a web browser using JavaScript

I am facing an issue with displaying files from a MSSQL Server Database that are stored as a column Content of type VARBINARY(MAX) in a SQL table. To access the database, I have developed a backend Node.js server using Express.js. There is a route called ...

Encountering a 404 error when utilizing ngx-monaco-editor within an Angular application

I have been encountering an issue while attempting to utilize the editor within my Angular 8 application. Despite researching similar errors on Stack Overflow and GitHub discussions, I haven't found a solution yet. Here's how my angular.json asse ...

Design for implementing "new" functionality in JavaScript

I recently delved into the world of JavaScript Patterns through Stoyan Stefanov's book. One pattern that caught my attention involves enforcing the use of the new operator for constructor functions, demonstrated with the following code snippet: funct ...

Encountering problems while compiling Laravel, Webpack, and Sparkline

Having trouble integrating the Sparkline JavaScript package into my Laravel 5.8 project using Laravel Mix. The Sparkline isn't displaying, and I'm encountering a browser console error. Error: Uncaught ReferenceError: sparkline is not defined. ...

What is the best way to transfer the entered data from a TextField into a form after the user clicks a

I have a Text Input field and a Button (both are material-ui components) displayed on my main page. I would like the ability to click the button and transfer the existing text from the input field into a form, without creating a duplicate field. The curren ...

Guide on transmitting data from a child component to a parent object in Vue.js?

When I attempt to utilize a child component with custom form inputs and emit those values to the parent component, I encounter an issue where one input value disappears when another input value is entered. Let me showcase some code: Child Component <tem ...

Is there a way to incorporate untyped ES6 react components into a Typescript component without specifying types for the JavaScript child components?

Imagine you have an ES6 component structured like this: component OldThing extends React.Component { constructor(props) { super(props); } render() { return <div>{this.props.someProp}</div>; } } Alongside, there's an ES6 ...