Combining Key-Value pairs in JavaScript using JSON

I am currently working on parsing a JSON object to extract the key and value combined into a variable. The desired output I want from the provided JSON is:

"/" - 7.84 GiB; "/opt" - 4.86 GiB; "/usr" - 4.80 GiB

While I can retrieve objects using my code snippet, I am facing difficulties in formatting the name and value as required. Any assistance would be greatly appreciated.

for (i = 0; i < obj.length; i++) 
{
 if  ( obj[i].name === 'mountpoints') 
 {
 js_mountpoints = obj[i].value;
 break;
 }
 js_mountpoints = 'NA';
}

This is the JSON input that I am working with:

[{
    "name" : "pe_build",
    "value" : "2016.2.1"
}, 
{
    "name" : "kernel",
    "value" : "Linux"
}, {
    "name" : "blockdevices",
    "value" : "sda,sdb,sr0"
},
{
    "name" : "mountpoints",
    "value" : {
        "\/boot\/efi" : {
            "size_bytes" : 261861376,
            "size" : "249.73 MiB",
            "capacity" : "0%"
        },
        "\/opt" : {
            "size_bytes" : 2086666240,
            "size" : "1.94 GiB",
            "capacity" : "1.64%"
        },
        "\/boot" : {
            "size_bytes" : 258650112,
            "size" : "246.67 MiB",
            "capacity" : "74.28%"
        },
        "\/var" : {
            "size_bytes" : 10475274240,
            "size" : "9.76 GiB",
            "filesystem" : "xfs",
            "capacity" : "4.01%"
        }
    }
    },  {
    "name" : "uptime_seconds",
    "value" : 244181
}, {
"name" : "memoryfree",
"value" : "6.66 GiB"
}, {
"name" : "memoryfree_mb",
"value" : 6816.91796875
}
]

Answer №1

result = ''
Object.keys(data).forEach(function(key) {
  if (data[key].property === 'mountpoints') { // retrieve sizes for mountpoints only
    var val = data[key].value;
    Object.keys(val).forEach(function(name) { // concatenate all sizes to result string
      result += '"' + name + '" - ' + val[name].size + ';';
    }); 
  }
}); 

if (result.length > 0) { // check if entries were added
  result.slice(0, -1);
}

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

Issue: Adjustment of elements' size using an "onclick" method when reaching specific screen width

Seeking assistance with implementing media queries in JavaScript. Can an object be resized from JavaScript code based on a specific screen width, rather than the default one? For example, if I have a button that opens a div with a height of 600px when cli ...

React Hamburger Menu not working as intended

I am facing an issue with my responsive hamburger menu. It is not functioning correctly when clicked on. The menu should display the navigation links and switch icons upon clicking, but it does neither. When I remove the line "{open && NavLink ...

Make the child div images disappear gradually and at the same time, make an overlapping parent div image appear using Javascript

Check out my attempt at solving this challenge on jsfiddle: http://jsfiddle.net/oca3L32h/ In the scenario, there are 3 divs within a main div. Each of these divs contains an image and they overlap each other. By using radio buttons, the visibility of the ...

Guide on updating a specific item in a JSON array using npm request

I am currently working on setting a value in a JSON array utilizing a PUT request with the request module, specifically targeting one of multiple main objects within the array. The structure is as follows: [ 0: { status: 'pending' ...

Eliminate Quotation Marks and Commas in String Data Using React

I created a code snippet to input data into a table and added a button function for downloading the entire table. However, when I open the downloaded file using notes or a text editor, it shows multiple double quotes and commas that I need to eliminate. He ...

Why is it possible for me to call a function that is defined below a component?

My understanding was that in Javascript, functions could not be invoked if they are defined below where they're called (unless hoisting is involved). However, I discovered something interesting while working with React. The code snippet below actuall ...

Experimenting with a function invoked from a jQuery AJAX callback using Jasmine testing framework

Currently, I'm working on a function that utilizes an AJAX call to interact with a service. My main goal is to ensure the displayError function is triggered in case of a failure. The ajaxCall function is set up to accept a URL parameter. When the req ...

The initial setTimeout function functions correctly, however the subsequent ones do not operate as expected

I have developed the following code: bot.on('message', message=> { if(message.content === "come here") { message.channel.send('hey'); setTimeout(() => { message.channel.send('i am here' ...

How to pass only the clicked element to the onClick function in React.js

I have several elements with the same className, and I want to add the className active to an element (with the className history-node) when it is clicked, in addition to its current className. However, I am facing an issue where the child elements of tha ...

What yields greater performance in MongoDB: employing multiple indexes or creating multiple collections?

Currently, I am developing an application that validates users through various 3rd party services such as Facebook and Google. Each user is assigned a unique internal id (uuid v4) which corresponds to their 3rd party ids. The mongoose schema for my user do ...

Converting a JavaScript variable into PHP using ajax: A comprehensive guide

Can someone please help me troubleshoot this code for passing a JavaScript variable to PHP? It doesn't seem to be working properly. I want to extract the value of an ID from JavaScript and send it over to PHP. <!DOCTYPE html> <html> ...

Using JavaScript to apply styling on images with overlays

I am currently facing an issue with placing an overlay on top of a background image. Despite my efforts, I am unable to get the background color to appear on top of the image. Any helpful suggestions on how to resolve this would be greatly appreciated. M ...

Avoid having the toast notification display multiple times

I've been working on implementing a toast notification for service worker updates in my project. However, I'm facing an issue where the toast notification pops up twice. It seems to be related to the useEffect hook, but I'm struggling to fig ...

Retrieving JSON information from the server

I have been working with the knockout.js framework and adapted a basic contacts form example to suit my needs. I am able to successfully store values in my database, but I am encountering difficulties when trying to load values from the server. Despite h ...

Flustered by a hiccup in the system, the flutter jsonDecode() function encounters an

While attempting to retrieve data from firestore, I encountered an error while trying to decode it. [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: FormatException: Unexpected character (at character 2) E/flutter (32531): {version: 0, ori ...

The architecture x86_64 is displaying undefined symbols for the JSONRPC library

Struggling with compiling an application using QT and the jsonRpc library includes: - libjson-rpc-cpp - jsoncpp Encountering this error during compilation: Undefined symbols for architecture x86_64: Json::Value::operator=(Json::Value const&am ...

Decomposing a Vuex module into distinct files with Nuxt: A step-by-step guide

In the official Nuxt documentation (here), it is mentioned that 'You can choose to divide a module file into separate files: state.js, actions.js, mutations.js, and getters.js'. While there are examples of breaking down the Vuex store at the roo ...

Angularjs drop-down menu changes images with animation

<body ng-controller="myCtrl"> <input type="checkbox" ng-model="loaded"/> <select ng-model="list"> <option ng-repeat="option in data.availableOptions" value="{{option.name}}">{{option.id}}</option> </select> {{list}} &l ...

The active tab will dynamically update, however, clicking anywhere on the page will always bring you back to the first tab as

My view includes the following tabs: <div class="tabbable"> <ul class="nav nav-tabs padding-18"> <li class="active"> <a aria-expanded="false" data-toggle="tab" href="#Tab1"> <i class="green ac ...

iOS6: Using POST method to send JSON data from an iPhone to a REST API

I have encountered an issue while trying to send data in JSON format to a REST API. The web service does not return any data when sending a parameter and instead shows the error message: Error parsing JSON: Error Domain=NSCocoaErrorDomain Code=3840 "The op ...