Creating a new JSON by extracting a specific branch or node from an existing JSON data

I have a Nuki Smartlock and when I make two API calls to the Nuki Bridge, I receive JSON responses. I want to apply the same logic to both responses:

When requesting for current states, the JSON looks like this:

[{
  "deviceType": 0,
  "nukiId": 1234,
  "name": "NukiDoor",
  "firmwareVersion": "2.9.10",
  "lastKnownState": {
    "mode": 2,
    "state": 3,
    "stateName": "unlocked",
    "batteryCritical": false,
    "batteryCharging": false,
    "batteryChargeState": 72,
    "doorsensorState": 2,
    "doorsensorStateName": "door closed",
    "timestamp": "2021-01-04T13:02:52+00:00"
  }
}]

And if I perform an Action (like opening the door), I get this additional JSON data:

{
  "deviceType": 0,
  "nukiId": 1234,
  "mode": 2,
  "state": 3,
  "stateName": "unlocked",
  "batteryCritical": "OFF",
  "batteryCharging": "OFF",
  "batteryChargeState": 72,
  "doorsensorState": 2,
  "doorsensorStateName": "door closed"
}

Therefore, the .lastKnowState node from the Status-Request matches the pure JSON structure of the Action-JSON.

To achieve this consistency in JavaScript, we need to "extract" the lastKnownState node from the first JSON response. How can this be done effectively?

Answer №1

In the data you are receiving, there is a JSON array containing one object which includes another nested JSON object called lastKnownState. To access the information within this nested object, you first need to extract the object at index 0 of the array. This will give you the outer JSON object that contains your desired lastKnownState. Then, you can use dot notation to specifically extract the details from the lastKnownState JSON.

For a more in-depth understanding of how to work with JSON objects and arrays, I recommend checking out the following resources: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics

You might also find this guide helpful: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON

const data = [{
  "deviceType": 0,
  "nukiId": 1234,
  "name": "NukiDoor",
  "firmwareVersion": "2.9.10",
  "lastKnownState": {
    "mode": 2,
    "state": 3,
    "stateName": "unlocked",
    "batteryCritical": false,
    "batteryCharging": false,
    "batteryChargeState": 72,
    "doorsensorState": 2,
    "doorsensorStateName": "door closed",
    "timestamp": "2021-01-04T13:02:52+00:00"
  }
}];

const lastKnownState = data[0].lastKnownState;

console.log(lastKnownState, null, 2)

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

Embedding Array into Mongodb is an efficient way to store and

Whenever I attempt to store array data within MongoDB using the query below, it always shows a success message without actually storing any data in an empty array inside MongoDB. My goal is to successfully store array data inside MongoDB as shown in the f ...

Strange transparency glitch in Three.js

I've run into a perplexing issue while creating a 3D model for my website. One of the character's arms appears to be transparent, but only partially - you can see inside it. Here's what I'm talking about: Transparent arm. I've trie ...

Transform the JSON array into a list of characters using ESQL

I am working with JSON syntax that looks like this: { "PRINTER": "P123", "ID_INPUT": "111046", "IDCOUNT": 3, "TIME": "", "IDLIST": [{ID_IN": "111046"},{" ...

Steps to prevent submission of input field until all necessary fields and checkboxes are filled, disabled the submit button

Check out my basic web application on this sandbox link: codesandbox.io/s/eager-kalam-v1lpg I need assistance with how to prevent the submit button from being enabled until all required fields and checkboxes are filled in. I am fairly new to working with ...

What is the correct method for launching a modal window in wagtail-admin?

I am currently working on enhancing my wagtail-admin interface, but I have hit a roadblock when trying to open a modal window. While I could create a div with a close button, I believe there must be a more appropriate method for achieving this. It seems th ...

JavaScript and CSOM updates cause SharePoint list item properties to disappear

Within my SharePoint environment, there exists a website where users can load a single list item based on their selection using JavaScript and CSOM. This particular list item contains approximately 60 properties defined in its list definition. Users have ...

The Ionic tab is already finished displaying even before the data has completed loading

Creating a favorites section for a vouchers app has proven to be slightly challenging. When attempting to retrieve the current user's favorite vouchers and display them using ngFor in the HTML, I encountered an issue. The very first time I open the fa ...

Converting a JSON array into a Java HashMap with Jackson: A step-by-step guide

I would like to use Jackson to convert the JSON array below into a Java HashMap, and then iterate over the values as shown: Desired output format: key Value 1 sql 2 android 3 mvc JSON Sample: enter code here { "menu": [ { ...

When attempting to use a value outside of its block, the function may return a

My current task involves querying one collection to retrieve IDs, then using those IDs to query another collection and send back the response. The process runs smoothly until I encounter an issue with retrieving values outside of a block when using forEach ...

Issue with Bootstrap 3 Modal: Missing Title and Input Labels

I'm currently working on customizing a bootstrap template for my friend's church website. My goal is to create a simple web presence for them, and I am in the process of setting up a contact form. I want this form to appear as a modal where users ...

The annoying Facebook "add a comment" popup refuses to close

Occasionally, the "add a comment" popup (iframe) in Facebook's Like plug-in fails to close and obstructs access to the content underneath. This issue has been noted while using Chrome 21 and Firefox 15. To replicate this problem, you can visit the fo ...

Learn how to utilize interpolation within an *ngIf statement in Angular 2 in order to access local template

Consider the following scenario; <div *ngFor="item of items; let i = index;"> <div *ngIf="variable{{i}}">show if variable{{i}} is true</div> </div> Suppose I have variables named "variable0", "variable1",... Is there a way to ac ...

Is there an alternative method to incorporate the 'environment.ts' file into a JSON file?

In my Angular application, I need to import assets based on the env configuration. I am attempting to extract the patch information from environment.ts and save it into my assets as a json file. However, I am unsure of the proper method to accomplish this. ...

Hide in certain zones, contextual menu

I recently discovered how to create my own context menu with links based on the div clicked (check out here for more details). However, I am facing an issue now. I am struggling to prevent the context menu from appearing above the specific div boxes where ...

Using JavaScript, implement the array.filter method on a JSON array to retrieve the entire array if a specific property matches a given

Help needed with filtering an array: In the user_array, there are arrays that need to be compared to see if the header_info.sap_number matches any value in the valid_sap_number array. If a property value matches anything in the valid_sap_number array, th ...

Utilizing modular structure for efficient jQuery AJAX request

Seeking guidance on optimizing multiple GET ajax calls, where each function contains repeated $.ajax({}) code lines. Is it feasible to create a single $.ajax({}) function and utilize it in all functions instead of duplicating the code? Perhaps something ...

What is the best way to automatically create a list of file names that can be used in a Grunt task?

I am currently utilizing load-grunt-config and grunt-prompt for my project development. I am working on an init task that involves moving php templates between folders. At the moment, I have hardcoded the template filenames, but I would prefer if Grunt co ...

How can one verify the presence and attributes of specific object properties by examining the Type object property?

My goal is to validate a JSON object with a complex schema. The example below may seem simple, but it effectively demonstrates the issue at hand. In the more intricate schema I'm working with, there needs to be an array of objects that adhere to cert ...

Vue Custom Element encountering issues when generating independent JavaScript files in the Dist directory

I recently followed the instructions for registering and utilizing custom elements as outlined here: https://alligator.io/vuejs/custom-elements/ For my project, I am using the standard Webpack template for Vue. After executing the command npm run buil ...

Checking if a Double variable is null can be done using the following method

When I access an endpoint and receive JSON data, I iterate through the object and assign the value to a double field. Occasionally, this field will be null. How should I address this null case in my code? Currently, it looks like this: double scanning_ris ...