Guide to parsing JSON data in JavaScript

As a newcomer to javascript, I recently received JSON data from the backend in my js file. The JSON data provided looks like this:

{
Vivo:{Time:[20190610,20190611],Price:[2000,2000]},
Huawei:{Time:[20190610,20190611],Price:[3000,3000]},
Maxvalue:3000
}

The JSON data was obtained using the following code:

fetch('/Tmall') //Tmall is the URL from where data is fetched
.then(function(response) {
return response.json();
}).then(function(Data) {

...
}

Now, I need to process the data to display it on the front-end, but I'm unsure of how to separate the data into two distinct variables:

Cellphone = 
{
Vivo:{Time:[20190610,20190611],Price:[2000,2000]},
Huawei:{Time:[20190610,20190611],Price:[3000,3000]}
}

Max = {Maxvalue:3000}

I attempted to use a conditional statement to extract the data, but it did not work as expected:

    var Cellphone = {}
    for (var i = 0; i < Data.length; i++)
    {
      if (Data.key[i] != 'Maxvalue'){
        Cellphone.push(Data[i])
      }
    }

Answer №1

To achieve this task, you can utilize a combination of Object.keys(), Array.prototype.filter(), and Array.prototype.map().

Check out the code snippet below:

// Sample `Data` object...
const Data = {Vivo:{Time:[20190610,20190611],Price:[2000,2000]},Huawei:{Time:[20190610,20190611],Price:[3000,3000]},Maxvalue:3000};

// Implementation
const Cellphone = Object.keys(Data)
  .filter(k => k !== 'Maxvalue')
  .map(k => ({ [k]: Data[k] }));
const Max = { Maxvalue: Data.Maxvalue };

console.log('Cellphone:', Cellphone);
console.log('Max:', Max);

Answer №2

To get the value of the property named Maxvalue and assign the rest to the Cellphone variable, you can use destructuring and spreading in a simple way:

const data = {
  Vivo: {
    Time: [20190610, 20190611],
    Price: [2000, 2000]
  },
  Huawei: {
    Time: [20190610, 20190611],
    Price: [3000, 3000]
  },
  Maxvalue: 3000
};

const { Maxvalue: Max, ...Cellphone } = data;
console.log("Max:", Max);
console.log("Cellphone:", Cellphone);
.as-console-wrapper { max-height: 100% !important; top: auto; }

Answer №3

If you want to extract the maximum value individually, you can store it in a variable and then remove it from the object. This method allows you to store all cellphones in a variable, even if their names change. For instance;

let data = {
  Vivo:{Time:[20190610,20190611],Price:[2000,2000]},
  Huawei:{Time:[20190610,20190611],Price:[3000,3000]},
  Maxvalue:3000
}

// store the maxValue in a variable
let maxValue = data.Maxvalue;

// remove the maxValue key from the object
delete(data.Maxvalue);

// the remaining keys represent cellphones
let cellPhones = data;

console.log(maxValue, cellPhones);

Answer №4

Within the function, when assigning Data as an argument, execute the subsequent steps:

let Mobile = {
    Samsung: Data.Samsung,
    iPhone: Data.iPhone
};
let Threshold = Data.ThresholdValue;

Answer №5

If you're facing an issue, the code snippet provided below should help address it:

let devices = {};
let largestValue;
Object.entries(data).forEach(function (entry) {
  if (entry[0] == "Maxvalue") {
    largestValue = entry[1];
  }
  else {
    devices[entry[0]] = entry[1];
  }
});
console.log("Devices: ", devices);
console.log("Largest Value: ", largestValue)

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

Change the behavior of a submit button to trigger a custom JavaScript function instead

I am faced with a challenge where I need to override the default functionality of a button in code that cannot be altered. Instead, I must ensure that when the button is clicked, a custom JavaScript method is called rather than submitting the form as it no ...

Sorry, I'm unable to determine the value of 'title' because it is undefined

Here is the code for the "singleCard" component. When passing {{card.title}} and {{card.body}}, an error occurs: **Error in render: "TypeError: Cannot read property 'title' of undefined" found in ---> <SingleCard> at src/components/sing ...

Decoding JSON data post transformation with XML2JSON

My task involves calling an API and receiving the response in XML format. I then utilize xml2json to convert the XML output into JSON. Now, my challenge is how to directly extract the temperature parameter value from the JSON output. This is the snippet o ...

When the page initially loads, the block appears on top of the upper block and remains in place after the page is refreshed

Upon initial loading, the block appears on top of another block but remains fixed upon page refresh. The same issue occurs in the mobile version of the site and occasionally displays correctly. The website is built on WordPress and optimized using Page Spe ...

"Integrating Associated Models with Sequelize: A Step-by-Step Guide

I am attempting to retrieve all transactions along with their associated stripePayments, but I keep encountering the error include.model.getTableName is not a function. In my database schema, there is a table for transactions that has a one-to-many relati ...

The attribute 'size' is not recognized within the data type 'string[]' (error code ts2339)

When using my Windows machine with VSCode, React/NextJS, and Typescript, a cat unexpectedly hopped onto my laptop. Once the cat left, I encountered a strange issue with my Typescript code which was throwing errors related to array methods. Below is the co ...

Converting JSON-style data into a string with the power of node mysql

Just a quick note - I'm a total newbie in the world of web development, so I might be missing an obvious solution here. My challenge is to insert a dataset into a MySQL database using nodejs/expressjs/mysql. I've managed to establish a connecti ...

Choosing comparable choices from the drop-down menu

I am working on a dropdown menu that contains different options. I need to use jQuery to automatically select the option that corresponds to the branch of the currently logged in user. However, when some option text is very similar, it causes an issue. // ...

Toggle menu visibility when body is clicked

<script> $(".bg").on('click', function(e) { e.preventDefault(); $("#navMenu").removeClass('open'); $("#searchBar").removeClass('active'); }); </script> My goal is to togg ...

The interaction issue in Ionic 4 with Vue js arises when the ion-content within the ion-menu does not respond to clicks

My Vue app has been set up with Ionic 4 using @ionic/vue. Below is the code snippet from the main.js file: import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store&apos ...

What is the best way to transmit the server response information from a fetch API to the client?

After receiving a response with the expected results from an API call using fetch API and a json object, I am looking for ways to send these results to the client in order to display them on the interface. The server-side operation was conducted through th ...

Storing knockout view model data in a database and fetching it back

I am currently working on a web form that utilizes knockout, and I need to add a new feature that allows users to save the form as a draft in the database. Later on, they should be able to load it again to make modifications or submit it. Is there a built ...

The conundrum with JQuery: My script refuses to run when a variable is defined

<script> $(document).foundation( let total = 1 $("button.test").click(function(){ if ($("p.change-me").text() === "OFF") { $("p.change-me").text("ON") total = total + 1 } ...

Using Express Router to serve and display static files in the public directory

The code snippet below is found in my index.js file: var express = require('express'); var app = express(); var PORT = 3000; var routes = require('./scripts/routes/routes'); app.set('views', './views'); app ...

Using VB.NET to run JavaScript through Selenium's ChromeDriver

I've tried various methods in C# but I can't seem to get them working in VB.NET. It's possible that I'm not initializing it correctly. My goal is to run javascript on a loaded URL using the chromedriver. This is what my code looks like ...

The .remove() method is ineffective when used within an Ajax success function

I am facing an issue with removing HTML divs generated using jinja2 as shown below: {% for student in students %} <div class="item" id="{{ student.id }}_div"> <div class="right floated content"> <div class="negative ui button compa ...

accessing a particular nested JSON object within multiple layers of JSON objects directly

Here is a sample JSON file: { "continue": { "rvcontinue": "20200228224232|943114133", "continue": "||" }, "query": { "pages": { "16152986": { "pageid": 161 ...

Please reset the form fields after the most recent edit

I've created a form that includes multiple select elements. When an option is selected, it activates the next select element and updates it with values using Ajax and PHP. However, I'm facing an issue where changing a previous option only resets ...

Identical code exhibiting varying behavior between localhost:3000 and the production server at localhost:5000 on the web

I'm currently in the process of learning React Js, but I've been encountering a persistent error that has me stumped. A specific component functions perfectly when running on my local server (localhost:3000), but as soon as I try to deploy it to ...

Error in 'Unity3D': Array Index Out Of Bounds Exception occurred while attempting to modify sprite upon collision

Hey there, fellow Developers! I know this question has been asked before, but none of the answers provided a solution to my specific problem. Just to give you some context, I am new to unity and currently working on creating a brick breaker game. The issue ...