Determining the presence of a nested JSON element

Upon receiving the JSON data, my task is to showcase three dates on a webpage categorized as: onsaleDate, focDate, and unlimitedDate. These specific dates are stored as "values" under the keys "date". Presently, I am fetching these dates using dates[0].date, dates[1].date, and dates[2].date. The challenge lies in the fact that not all instances of dates will contain all three types - onsaleDate, focDate, and unlimitedDate. How can I verify the presence of these date types before assigning them to a variable for display on the page? Would a conditional loop be necessary? Is it feasible to use hasOwnProperty for nested items?

"results": [
   "dates": [
       {
         "type": "onsaleDate",
         "date": "2011-10-12T00:00:00-0400"
       },
       {
         "type": "focDate",
         "date": "2011-09-12T00:00:00-0400"
       },
       {
         "type": "unlimitedDate",
         "date": "2012-12-18T00:00:00-0500"
       },
       {
         "type": "digitalPurchaseDate",
         "date": "2012-05-01T00:00:00-0400"
       }
     ]

Answer №1

If you need to determine the existence of a specific type within an object in an array, you can utilize the find method:

results.dates.find(obj => obj.type === "onsaleDate")

To make this more versatile, you can create a small function that accepts a property name as an argument and returns a function suitable for use with find:

function checkType(type) { 
  return function(o) { return o.type === type; };
}

You can now easily verify the presence of 'onsaleDate' by using:

results.dates.find(checkType("onsaleDate"))

Alternatively, you can search for all three types like so:

results.dates.find(checkType("onsaleDate")) && results.find(checkType("...

Or, if you prefer:

["onsaleDate", "focDate", "unlimitedDate"] . 
  every(type => results.dates.find(checkType(type)))

Answer №2

To address this problem, I would resolve it by changing the data type of the output:

output = JSON.parse(output);
var datesList = {};
output.datesList.forEach(item => datesList[item.category] = item.date);
output.datesList = datesList;

//you can now retrieve them using
if(output.datesList.saleDate){
  // show sale date....
}

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

Tips on transitioning from Modal1 to Modal2 in Ionic after a successful submit button press?

My survey app requires users to fill out a form and click the Submit Feedback button. Upon successful submission, a message saying "Feedback submitted successfully" should be displayed in Modal2, which is inside another modal named (Modal1). However, being ...

During the installation process of Next JS, I faced a challenge that hindered

While setting up NextJS, I ran into the following issue: D:\Codes\React\Learn>npx create-next-app npm WARN using --force Recommended protections disabled. npm WARN using --force Recommended protections disabled. npm ERR! code E404 npm ERR ...

Querying Firebase by the value of a child node

Here is how my structure looks like: 2017511 UcQefEaHJG6fteGsbsiaWjQ60d9Q62 value1: 50 value2: 1200 value3: "blabla" AcQefEaHJG6fteGsbsiaWjQ60d9Q62 value1: 55 value2: 2200 value3: "balabla" BcQefEaHJG6fteGsbsiaWjQ6 ...

Generating JSON array objects dynamically in JavaScript code

Need help with organizing my code let newArr = []; $.post( "/reports/search", { query:'*'},function(data) { for(let i=0; i<data.length; i++) { newArr[i].value = data[i].name; newArr[i].data = data[i].id; } },'json ...

What is the best way to implement the nth:child selector in conjunction with the each function for handling JSON data in

Here is the HTML code I have written: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Flickr Feed</title> <link href="../_css/site.css" rel="stylesheet"> <link rel="stylesheet" type= ...

The selected value in the ng-model is not defined

In my HTML, I have a select box with options generated from an ng-repeat. <select ng-model="pageId" ng-change="setFacebookPage()"> <option ng-repeat="page in pages" ng-value="page.id"> {{page.name}}</option> </select> Everythi ...

obtain information beyond the prescribed boundaries

Having a slight issue, I am trying to return an array using a function in Angular. I am processing my data within an anonymous function and when I try to return the array, it ends up empty. I'm not sure what to do... getCurrentExchangeTo : function( ...

Excluding specific key elements from a JSON file through filtering

I'm struggling with filtering a non-standard JSON file. The file consists of multiple JSON objects on separate lines, and I need to check each object for specific keys (e.g. "name" or "firstname"). If the object contains either of these keys, I want t ...

Jquery UI Dragging Feature Disabled After Element Dropped

Here is the code I have written: <!doctype html> <html lang="en"> <head> <meta charset="utf-8> <meta name="viewport" content="width=device-width, initial-scale=1> <title>jQuery UI Droppable - Default function ...

Having trouble implementing styles for an element selected using the document.getElementsByClassName() method

In order to adjust the style of a dropdown menu, I need to change its top value to align it properly. The element is being generated by Drupal (a CMS tool) and is configured with classes for styling purposes in the admin view where content is authored. How ...

Exploring the concept of event delegation: Understanding the difference between Event.target and

In the MDN Event.target reference, there is an example provided regarding event delegation: Example of Event Delegation // Assuming there is a 'list' variable containing an instance of an // HTML ul element. function hide(e) { // Unless l ...

Floating action button within a collapsible panel

I am having trouble placing a fixed-action-btn inside a collapsible body. It keeps appearing in the bottom right corner of the page instead of within the collapsible itself. How can I ensure that the button stays inside the body? Check out this link for r ...

Dealing with 404 errors encountered when making requests to external websites, utilizing either basic Javascript or JQuery

I have links in my application that redirect to external websites. For example, a link might look like this: <http://www.google.com'>>General Search<>. Users input the href and we dynamically create the link without any validation of it ...

How can you navigate to the left within a component by scrolling?

My Panel component is equipped with an overflow-x: scroll; feature for horizontal scrolling. Given the large amount of data it contains, I am looking for a way to enable horizontal scrolling within the panel. What is the best approach to achieve this? Is ...

Exploring Vue JS: Decoupling variables in separate files and effective ways of accessing them

In my Vue project, I am looking to create a dedicated .js file to store multiple variables that can be easily accessed by other components. I am seeking advice on the most efficient method to achieve this and would greatly appreciate any examples provide ...

Is it possible to update a module on an end user's device without using npm or node.js?

Currently, I am working on developing an electron application along with a module that it uses. My main concern is ensuring that this module gets updated on the end user's machine whenever there is a new version available, even if they do not have NPM ...

"Exploring Different Layouts in Mean.js: Whether on the Server Side or leveraging

I have been working on a mean.js application and I am currently trying to integrate an admin theme with the existing project. My query is: Is it possible to have multiple server layouts? For example, can we use layout-1 for regular users and layout-2 fo ...

Combining and serializing a JavaScript object

Combining nested JavaScript objects was straightforward when dealing with a single object. However, as the number of objects has increased, I require a more dynamic approach to merge the address key and serialize my object. var old = {account: "100000 ...

What is the best way to modify the colors of two specific elements using a combination of CSS and JavaScript

I am currently developing a browser-based game and have encountered an issue. Here is the relevant line of my HTML/PHP code: echo '<div id="div'.$n.'" class="d'.$rand.'" onclick="swapit(this.id, this.className)"></di ...

Is it possible for us to perform an addition operation on two or more items that belong to the same

I am faced with a challenge involving 3 objects of the same type, each having different values for their properties. My goal is to add them together as illustrated below: Consider this scenario: objA = { data: { SH: { propertyA: 0, propertyB: ...