A guide on organizing nested JSON objects in JavaScript

I am currently using JavaScript to retrieve JSON data that looks like this:

[{
    "data": {
        "serialNumber": "12345678",
        "loopCount": 2,
        "temperature3": 22.74921781259558,
        "temperature2": 21.459065450414467,
        "temperature1": 25.60573959350586,
        "temperature7": 20.560272859443444,
        "temperature6": 24.672770566493245,
        "temperature5": 21.418451432003607,
        "temperature4": 24.136719323883636,
        "temperature8": 23.106006457744044
    },
    "deviceID": "12345678",
    "timestamp": "1514876959940"
}, {
    "data": {
        "loopCount": 3008,
        "serialNumber": "12345678",
        "temperature3": 24.340541769172475,
        "temperature2": 24.592980449259386,
        "temperature1": 25.208276748657227,
        "temperature7": 22.95620713734396,
        "temperature6": 24.173083663793975,
        "temperature5": 22.274865355495226,
        "temperature4": 23.507075904805543,
        "temperature8": 20.596809083024773
    },
    "deviceID": "12345678",
    "timestamp": "1514910791413"
}]

My goal now is to reorganize the JSON object using JavaScript so that it appears as follows:

[{
    "loopCount": 3009,
    "serialNumber": "12345678",
    "temperature3": 20.938793894509594,
    "temperature2": 20.631314982104072,
    "temperature1": 25.192977905273438,
    "temperature7": 21.514532309261064,
    "temperature6": 24.03336173424463,
    "temperature5": 23.453609565992643,
    "temperature4": 24.424291668247513,
    "temperature8": 22.044323519108403,
    "timestamp": "1514910802296"
}, {
    "loopCount": 3009,
    "serialNumber": "12345678",
    "temperature3": 20.938793894509594,
    "temperature2": 20.631314982104072,
    "temperature1": 25.192977905273438,
    "temperature7": 21.514532309261064,
    "temperature6": 24.03336173424463,
    "temperature5": 23.453609565992643,
    "temperature4": 24.424291668247513,
    "temperature8": 22.044323519108403,
    "timestamp": "1514910802296"
}]

Presently, this is my current implementation:

  var myObj =[{
"data": {
"serialNumber": "12345678",
"loopCount": 2,
"temperature3": 22.74921781259558,
"temperature2": 21.459065450414467,
"temperature1": 25.60573959350586,
"temperature7": 20.560272859443444,
"temperature6": 24.672770566493245,
"temperature5": 21.418451432003607,
"temperature4": 24.136719323883636,
"temperature8": 23.106006457744044
},
"deviceID": "12345678",
"timestamp": "1514876959940"
},  {
"data": {
"loopCount": 3008,
"serialNumber": "12345678",
"temperature3": 24.340541769172475,
"temperature2": 24.592980449259386,
"temperature1": 25.208276748657227,
"temperature7": 22.95620713734396,
"temperature6": 24.173083663793975,
"temperature5": 22.274865355495226,
"temperature4": 23.507075904805543,
"temperature8": 20.596809083024773
},
"deviceID": "12345678",
"timestamp": "1514910791413"
}, {
"data": {
"loopCount": 3009,
"serialNumber": "12345678",
"temperature3": 20.938793894509594,
"temperature2": 20.631314982104072,
"temperature1": 25.192977905273438,
"temperature7": 21.514532309261064,
"temperature6": 24.03336173424463,
"temperature5": 23.453609565992643,
"temperature4": 24.424291668247513,
"temperature8": 22.044323519108403
},
"deviceID": "12345678",
"timestamp": "1514910802296"
},  {
"data": {
"loopCount": 3462,
"serialNumber": "12345678",
"temperature3": 20.927366751292798,
"temperature2": 23.690258459678994,
"temperature1": 24.851139068603516,
"temperature7": 22.797037129771063,
"temperature6": 24.46046332152272,
"temperature5": 24.415112076761666,
"temperature4": 21.217672372617155,
"temperature8": 20.609864963787967
},
"deviceID": "12345678",
"timestamp": "1514915728668"
}]



for (var key in myObj) {
document.getElementById("demo").innerHTML += myObj[key].data.serialNumber + "<br>";
document.getElementById("demo").innerHTML += myObj[key].data.loopCount + "<br>";
document.getElementById("demo").innerHTML += myObj[key].timestamp + "<br>";
document.getElementById("demo").innerHTML += myObj[key].data.temperature1 + "<br>";
document.getElementById("demo").innerHTML += myObj[key].data.temperature2 + "<br>";
document.getElementById("demo").innerHTML += myObj[key].data.temperature3 + "<br>";
document.getElementById("demo").innerHTML += myObj[key].data.temperature4 + "<br>";
document.getElementById("demo").innerHTML += myObj[key].data.temperature5 + "<br>";
document.getElementById("demo").innerHTML += myObj[key].data.temperature6 + "<br>";
document.getElementById("demo").innerHTML += myObj[key].data.temperature7 + "<br>";
document.getElementById("demo").innerHTML += myObj[key].data.temperature8 + "<br><br>";
}
<!DOCTYPE html>
<html>
<body>

<p>How to access nested JSON objects.</p>

<p id="demo"></p>


</body>
</html>

Answer №1

Utilizing ES7, one can leverage map and spread in the following way:

data.map(x => ({ ...x.data, timestamp: x.timestamp }))

In ES6, the spread operator is not used:

data.map(x => Object.assign({}, x.data, { timestamp: x.timestamp }))

Answer №2

I want to transform the structure of the JSON object using JavaScript so it appears like this.

You can achieve this by utilizing the map function.

var array = [{    "data": {        "serialNumber": "12345678",        "loopCount": 2,        "temperature3": 22.74921781259558,        "temperature2": 21.459065450414467,        "temperature1": 25.60573959350586,        "temperature7": 20.560272859443444,        "temperature6": 24.672770566493245,        "temperature5": 21.418451432003607,        "temperature4": 24.136719323883636,        "temperature8": 23.106006457744044    },    "deviceID": "12345678",    "timestamp": "1514876959940"}, {    "data": {        "loopCount": 3008,        "serialNumber": "12345678",        "temperature3": 24.340541769172475,        "temperature2": 24.592980449259386,        "temperature1": 25.208276748657227,        "temperature7": 22.95620713734396,        "temperature6": 24.173083663793975,        "temperature5": 22.274865355495226,        "temperature4": 23.507075904805543,        "temperature8": 20.596809083024773    },    "deviceID": "12345678",    "timestamp": "1514910791413"}];

var result = array.map((obj) => ({...obj.data, timestamp: obj.timestamp}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Implementing a Button Click Event Listener on a Separate Component in React

Currently, my React application incorporates MapBox in which the navbar is its parent component. Within the navbar component, there is a button that collapses the navbar when clicked by changing its CSS class. I also want to trigger the following code snip ...

Parsing JSON data into nested C# objects

Note: Just to clarify, I do not have control over the JSON structure, and I understand that ideally my C# object should align with the JSON format. My question isn't about why the deserialization is not working as expected; rather, I am wondering if t ...

React & Material UI: Unleashing the Power of Chained Arrow Functions

I stumbled upon this code snippet while browsing through the Material UI docs on Accordion. Despite spending hours trying to understand it, I'm still struggling to grasp its functionality: export default function CustomizedAccordions() { const [expa ...

Executing API call utilizing the Request module within a node.js application

In my node.js app, I have a request call that looks like this: request({ url:chanURL, qs:chanProperties}, function(err, response, body) { if(err) { console.log(err); return; } body = JSON.parse(body); (function (body) { Objec ...

JavaScript Class vs Function as Definition

Having trouble locating documentation for this issue. I devised a JavaScript class in the following manner: class Polygon { constructor(height, width) { this.height = height; this.width = width; } area = function() { return this.height ...

Ways to address a buffered data problem in Websocket Rxjs. When trying to send a message, it is not being received by the server and instead is being stored in a

Currently, I am utilizing Websocket Rxjs within my application. The connection is successfully established with the server, and upon subscribing to it, all data is received in an array format. However, when attempting to send data back to the server, it se ...

Issue: ParserError encountered due to a Syntax Error found at line 1, column 32

As a beginner in programming, I am encountering an issue. When I run "npm run build" in the Terminal to compress my project in React.js, I encounter this error. Interestingly, I have previously created another project without facing this problem, and I can ...

Tips for automatically incorporating animation upon page initialization

I'm looking to add an automatic image effect when the page is loaded. I currently have this code in my js file: $(window).ready(function(){ $(pin).click(function(){ $("#pin01").show().animate({left: '650px'}); }) }); Here is the HTML wit ...

Update data dynamically on a div element using AngularJS controller and ng-repeat

I am currently navigating my way through Angular JS and expanding my knowledge on it. I have a div set up to load data from a JSON file upon startup using a controller with the following code, but now I am looking to refresh it whenever the JSON object cha ...

Error Message: Unable to retrieve property "country" as the variable this.props is not defined

Currently, I am developing a react application However, when running this function using infinite scroll, an error is encountered An Unhandled Rejection (TypeError) occurs: Unable to access the "country" property, since this.props is undefined async pa ...

Utilizing Async and await for transferring data between components

I currently have 2 components and 1 service file. The **Component** is where I need the response to be displayed. My goal is to call a function from the Master component in Component 1 and receive the response back in the Master component. My concern lies ...

Sending a JSON object with scheduled task cron job

I have a PHP cron job that is quite complex. It retrieves data from an external webpage and consolidates all the information into one variable, encoding it in JSON. Unfortunately, this entire process is slow and consumes a significant amount of time. My d ...

Close the Bootstrap Modal by clicking the back button within SweetAlert

**How can I close a Bootstrap modal when clicking the back button in SweetAlert? I have tried using modal.hide() but it's not working. I am using Bootstrap version 5 and even checked their documentation with no luck. Does anyone know how to achieve th ...

The JavaScript confirm function will provide a false return value

Is it necessary to display a confirmation message asking "Are you sure ..."? I have implemented the message, but the function return false; is not working when the user clicks NO. <script> function confirmDelete(){ var answer = confirm("Are you su ...

Sync JSON object modifications with the DOM using jQuery (or potentially other libraries)

I am working on developing a web application that would be able to update the HTML elements based on changes in a JSON object. For instance, I have an unordered list with data attributes: <ul data-id="elements"> <li data-id="01">Element 01< ...

Execution priority of Javascript and PHP in various browsers

I implemented a basic JavaScript function to prevent users from using special characters in the login form on my website: $("#login_button").click(function(){ formChecker(); }); function formChecker() { var checkLogin = docum ...

Can you explain the distinctions between Rundeck and Quartz in terms of their job scheduling capabilities?

In my quest for a job scheduler compatible with both node.js and Rundeck, I stumbled upon Quartz. However, despite my efforts to grasp the differences between Quartz and Rundeck, I find myself at a loss. Any assistance on this matter would be immensely a ...

The request to http://localhost:3000/cartdata has encountered an internal server error (500) in the isAxiosError.js file at line

Error Image I'm currently working on developing a shopping cart feature, and I've encountered an issue when transferring data from the client side to the server side. Despite the cart data being successfully updated in the session, an internal se ...

Angular 14 is experiencing issues with NgRx Store failing to properly recognize the payload

The issue lies in TypeScript not recognizing action.payload.index as a valid property. I am unsure how to resolve this problem and make the 'index' visible in my project. shopping-list.actions.ts import {Action} from "@ngrx/store"; im ...

Is there a way to check if a file name input is valid using regular expressions?

I'm having trouble getting my code below to work properly. I'm not sure if the problem lies in the match function syntax or the regex itself. Any assistance would be greatly appreciated. $scope.fileSelected = function (file) { var valid = "/ ...