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

Associate a unique identifier string with a randomly generated integer identifier by Agora

For my current web project, I am utilizing a String username as the UID to connect to the channel in an Agora video call. However, I now need to incorporate individual cloud recording by Agora into the project. The challenge lies in the fact that cloud r ...

Ways to conceal images until AFTER the completion of the jquery flexslider loading process

After trying to integrate wootheme's Flexslider on my website, I encountered a small issue with its loading process. Whenever the page is refreshed with the slider, there is a brief moment (approximately 1 second) where the first slide appears overly ...

Waiting for update completion in Firebase Firestore (Javascript for web development)

When I retrieve a document, update it, and then try to access the updated data, I am getting undefined logged. Can anyone explain why this is happening and suggest a solution for successfully fetching the new data from the document? db.collection("collect ...

The function react.default.memo is not recognized at the createSvgIcon error

After updating my Material-UI version to 1.0.0, I encountered a peculiar error message stating that _react.default.memo is not a function at createSvgIcon Despite attempting to downgrade the react redux library to version 6.0.0 as suggested by some ...

Navigational paths for the persistent sidebar in Material UI

I am looking to utilize this as a page navigation, but I am struggling with properly linking it to the index. I have attempted separating the items, but that approach did not work as intended. <List> {['Home' , 'Abo ...

In JavaScript, filter out an array of image links that end with .jpg, .jpeg, .png, or

Need assistance, could someone lend a hand? I've got an array of image URLs and I'm attempting to filter out only the links with supported images using regex or endsWith(). It's been a struggle all morning. Appreciate any help offered! ...

How to retrieve the ID of the inserted record in Knex.js

I was trying to add a new note to the quoteNotes table. However, after inserting it and logging the response, I noticed that there was no record of the inserted note showing up. router.post('/:id/notes', (req, res) => { const {id} = req.para ...

Where can I locate the list of events supported by CKEditor 4?

Looking for the list of available events I attempted to locate the event list in the official documentation, but unfortunately came up short. I resorted to searching through the source code using .fire("/s+") to identify all available events. However, thi ...

Issues with AngularJS service not properly parsing JSON data retrieved through HTTPGET请求

I'm struggling to send a HTTP request to a WebAPI using an AngularJS service and display an HTML page with two nested ng-repeat's (posts and replies). The {{ post.displayName }} is showing up in my browser, but the replies are not loading. Can so ...

Issue with Loading Data on AJAX Causing Scrolling Difficulties

Currently, I am in the midst of website development using PHP, MySQL, and JavaScript (JQuery + Ajax). One issue that has arisen is with the customer scroll function and scrollbars. When loading data via ajax, the scroll function is generating numerous erro ...

What drawbacks should be considered when utilizing meteor.js for development?

After viewing the meteor.js screencast, I was truly impressed by its seamless web application development capabilities, especially in terms of live updates and database synchronization. However, I am curious about its scalability once the website goes live ...

One way to change the cursor CSS property is by dynamically altering it based on scrolling behavior. This involves modifying the cursor property when scrolling

I'm attempting to adjust the cursor property within an Angular function. The issue I'm facing is that when I begin scrolling the webpage, the cursor changes to a pointer, but when I stop scrolling, it remains as a pointer. I've attempted to ...

Personalizing text in HTML using JavaScript results

I have a modal dialog box function that pops up when a user clicks a button, triggered by a javascript/jquery script. The text displayed in the dialog is set up within an HTML div element that references the script function. My query is how to personalize ...

Guide to loading a minified file in Angular 2 with Gulp Uglify for TypeScript Bundled File minimization

In my Angular 2 application, I have set the TypeScript compiler options to generate a single outFile named Scripts1.js along with Scripts1.js.map. Within my index.html file: <script src="Scripts/Script1.js"></script> <script> ...

Angular 16 SSR encounters a TypeError when the 'instanceof' operator is used on a value that is not an object

I have been facing an issue while updating my Angular application from version 15 to 16. Everything seems to work fine with Angular, including building for Angular Universal without any errors. However, when I attempt to serve using npm run serve:ssr, it t ...

Angular is facing difficulties in loading JSON data from Rails

Within my Rails backend, I have a method designed to retrieve data from the database and convert it into JSON: def index @airports = Airport.select('id,city,country') render status:200, json: { airports: @airports } end In addition, ...

What is the reason for the value of an object's key becoming undefined when it is set within a loop?

I've always wondered why setting a certain object's key as its own value in a loop results in undefined. Take this code block, for example: var text = 'this is my example text', obj = {}, words = text.split(' '); for (i = ...

"Successfully implementing AJAX POST functionality, but encountering issues where callbacks are not triggering

I have gone through numerous posts addressing this issue and attempted various solutions, however, none seem to work for me. My AJAX POST function correctly adds the email to my mailing list, but the success and error callbacks are not consistently firing, ...

Angular Compilation Blocked Due to Circular Dependency Error

Currently, I am utilizing WebStorm as my IDE to work on a personal project that I envision turning into a game in the future. The primary goal of this project is to create an Alpha version that I can showcase to potential employers, as I am actively seekin ...

Prevent zooming or controlling the lens in UIWebview while still allowing user selection

Is there a way to disable the zoom/lens on uiwebview without affecting user selection? I'm trying to avoid using "-webkit-user-select:none" in my css. -webkit-user-select:none ...