Checking for the presence of a certain key within an object containing arrays that are value-based rather than index-based, using a Javascript

As I've been exploring various code snippets to check for the presence of object keys within arrays, I came across some brilliant examples that have been really helpful...

However, my current dilemma lies in dealing with a JSON response that requires specific key values to access items within an array. Take a look at the "orders" section:

{"Routes": [
     {
        "route": {
            "id": "1daf1f53-80b6-49d6-847a-0ee8b814e784-20180821"
        },
        "vehicle": {
            "id": "1daf1f53-80b6-49d6-847a-0ee8b814e784"
        },
        "driver": {
            "id": "6c2823be-374e-49e5-9d99-2c3f586fc093"
        },
        "orders": {
            "6df85e5f-c8bc-4290-a544-03d7895526b9": {
                "id": "6df85e5f-c8bc-4290-a544-03d7895526b9",
                "delivery": {
                    "customFields": {
                        "custom": "5379"
                    }
                },
                "isService": true
            }
         }    
   }
    ]
};

The code logic functions perfectly until it reaches the point where a specific key value needs to be provided:

function checkProperty(obj, prop) {
  var parts = prop.split('.');
  for (var i = 0, l = parts.length; i < l; i++) {
    var part = parts[i];
    if (obj !== null && typeof obj === "object" && part in obj) {
      obj = obj[part];
    } else {
      return false;
    }
  return true;
}

Below are some test scenarios showcasing both successful and unsuccessful outcomes:

console.log(checkProperty(test, 'Routes.0.orders'));  //Valid - returns true
console.log(checkProperty(test, 'Routes.0.orders.id'));  //Invalid - returns false
console.log(checkProperty(test, 'Routes.0.orders.6df85e5f-c8bc-4290-a544-03d7895526b9.id)); //Invalid - returns false

I seem to be stuck and any assistance would be greatly appreciated...

Answer №1

 "requests": {
            "95b1a9b7-2f91-427d-a96e-b78abfc7f22b": {
                "id": "95b1a9b7-2f91-427d-a96e-b78abfc7f22b"

fourth test:
Id is not a direct descendant of "Requests" as shown in your sample: requests.95b1a9b7-2f91-427d-a96e-b78abfc7f22b.id

fifth test:
There is a syntax error in the fifth case - a missing '|'

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

Neglect to notify about the input text's value

Having trouble retrieving the text from a simple <input id="editfileFormTitleinput" type="text>. Despite my efforts, I am unable to alert the content within the input field. This is the code snippet I've attempted: $('#editfileFormTitleinp ...

What steps can be taken to resolve the error message "AttributeError: 'WebElement' object does not have the attribute 'find_element_class_name'?"

try: main = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "main")) ) articles = main.find_elements_by_tag_name("article") for article in articles: header = article.find_element_c ...

Ways to incorporate conditional checks prior to running class methods

Seeking input on handling async data retrieval elegantly. When initializing a class with asynchronous data, I have been following this approach: class SomeClass { // Disabling strictPropertyInitialization private someProperty: SomeType public asy ...

Ways to eliminate existing information when conducting a search

Recently, I was tasked with integrating a search engine into a website that already has a list of data displayed on the first page. The challenge I faced was figuring out how to hide or remove this existing data when a new search request is made. You can v ...

Sinon respects my intern functions during testing in ExpressJS

At the moment, I am working on incorporating sinon stubs into my express routes. However, I am facing an issue where my functions are not being replaced as expected. I would like my test to send a request to my login route and have it call a fake function ...

Parsing JSON to create a specialized list

I have a JSON object that looks like this: var data = [ [99, "abc", "2dp", {"GroupNum": 0, "Total": [4, 1]}], [7, "x", "date"], [60, "x", "1dp", {"GroupNum": 1}], ... ] Here are the rules for this data (with i representing the inner list ...

Inquiries about JavaScript and the YouTube API

Being very resourceful, I am currently exploring ways to feature my YouTube links on my website in an elegant manner. Tired of the redundancy of posting on both platforms, I am seeking a solution that seamlessly integrates these posts. Despite my efforts, ...

Slicing dynamic arrays in Numpy using minimum and maximum boundaries

Within my 3D array, shaped as (365, x, y), the axis corresponding to daily data contains instances where all elements are np.nan. The time series along the axis=0 takes on this form: https://i.stack.imgur.com/JAcHQ.png To identify the index of the peak ...

Best practices for alerting using React and Redux

As I delve into Redux for the first time and work on revamping a fairly intricate ReactJS application using Redux, I've decided to create a "feature" for handling notifications. This feature will involve managing a slice of state with various properti ...

Trigger offcanvas modal and backdrop simultaneously using Bootstrap v5.0

Working with Bootstrap v5.0 offcanvas has been smooth sailing until I hit a roadblock. Clicking on the offcanvas button seems to be triggering both the offcanvas-backdrop and modal-backdrop divs simultaneously. <div class="modal-backdrop fade show ...

"Commitment made ahead of time without allowing for the outcome to

I'm completely new to working with promises and I'm encountering some unexpected behavior in my code. The issue lies in the TaskRunner.SyncObjects function within Main.js, which should be waiting for the selectedCourses variable to be populated ...

When trying to use setInterval () after using clearInterval () within an onclick event, the functionality seems

Can anyone assist me with an issue I am encountering while using the setInterval() function and then trying to clear it with clearInterval()? The clearInterval() works fine, but the automatic functionality of li elements with a specific class suddenly stop ...

Steps to import a JSON file into a PostgreSQL database

Looking to import a JSON file into PostgreSQL with the following sample data: { "asin":"2094869245", "title":"5 LED Bicycle Rear Tail Red Bike Torch Laser Beam Lamp Light", "price":8.26, "imhUrl":"http://ecx.images-amazon.com/images/I/51RtwnJwtBL ...

Employing the JSON return code

I am attempting to implement ajax with php. Here is the PHP script I have: <?php // This file retrieves the POST information sent by an AJAX request and returns the values if successful. $price['name'] = "Called"; $price['Wheel'] ...

Understanding how JSON.net can parse DateTime objects with timezone offsets is crucial for working

When calling a web service, I receive an item with the following property: "startDate":"/Date(1398859200000+1100)/" In my C# code, I define a class like this: public class MyClass { public DateTimeOffset StartDate {get; set;} } For unit testing pu ...

JavaScript: Manipulating Data with Dual Arrays of Objects

//Original Data export const data1 = [ { addKey: '11', address: '12', value: 0 }, { addKey: '11', address: '12', value: 0 }, { addKey: '12', address: '11', value: 0 }, { addKey: &a ...

Is Jade used for making subsequent lines children of an included partial?

Recently, I've encountered an issue with a basic jade layout. Here is an example: include test.jade #bar hi In the test.jade file: #foo hello No matter what I try, the #bar element always ends up as a child of #foo. <div id="foo">hello &l ...

The inner workings of v8's fast object storage method

After exploring the answer to whether v8 rehashes when an object grows, I am intrigued by how v8 manages to store "fast" objects. According to the response: Fast mode for property access is significantly faster, but it requires knowledge of the object&ap ...

Tips for transferring data between iframes on separate pages

I am currently working on implementing a web calendar module within an iframe on page-b. This module consists of 1 page with two sections. Upon entering zipcodes and house numbers, the inputs are hidden and the calendar is displayed. The technology used he ...

Communicating JSON data through AJAX with a WCF web service

Hey everyone, I could really use some assistance with my current coding issue. My goal is to pass the value 2767994111 to my WCF web service using jQuery AJAX. var parameter = { value: "2767994111" }; $('#btSubmit').click(function () { $ ...