Ways to extract the names of a JSON object using Angular

In my dataset, I have information about block devices with specific attributes such as Backend_Device_Path, Capacity, Bytes_Written, etc.

$scope.mydata = [{
    "Block_Devices": {
        "bdev0": {
            "Backend_Device_Path": "/dev/ram1",
            "Capacity": "16777216",
            "Bytes_Written": 1577,
            "timestamp": "4365093970",
            "IO_Operations": 17757,
            "Guest_Device_Name": "vdb",
            "Bytes_Read": 17793,
            "Guest_IP_Address": "192.168.26.88"
        },
        "bdev1": {
            "Backend_Device_Path": "/dev/ram2",
            "Capacity": "16777216",
            "Bytes_Written": 1975,
            "timestamp": "9365093970",
            "IO_Operations": 21380,
            "Guest_Device_Name": "vdb",
            "Bytes_Read": 20424,
            "Guest_IP_Address": "192.168.26.100"
        }
    },
    "Number of Devices": 2
}]

I want to extract the names of these objects and create an array like this:

devices = ['bdev0', 'bdev1']

When trying $scope.mydata.Block_Devices, it returns the entire JSON object. How can I only retrieve the object names (i.e bdev0 and bdev1)?

Answer №1

Give this a shot:

let devices = [];

for (const key in $scope.mydata[0].Block_Devices) {
    devices.push(key);
}

Answer №2

A handy ES5 method

keys = Object.keys($scope.mydata[0].Block_Devices)

Answer №3

To achieve this, you need to iterate through the object's properties:

const devicesList = [];
const data = $scope.mydata[0].Block_Devices;

for (let propertyName in data) {
  if (data.hasOwnProperty(propertyName)) {
    devicesList.push(propertyName);
  }
}

Using the hasOwnProperty method is crucial to avoid including properties from the prototype chain. If you are certain that there are no such properties, you can skip this check.

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

Guide to installing angular-ui-bootstrap through npm in angularjs application

My goal is to incorporate angular-ui-bootstrap into my project using the following steps: 1. npm install angular-ui-bootstrap 2. import uiBootstrap from 'angular-ui-bootstrap'; 3. angular.module('app', [      uiBootstrap    ]) I ...

Transferring a list of decimal numbers from a Python server to another using Flask and the requests library

I am working on a project that involves periodically sending an Array of doubles from a Python service to another. Despite being a newcomer to Python, I have delved into topics like Flask and requests. Below is a basic code example that I put together jus ...

When the nav-element is clicked, it will load the new content/file.php into the div with the id of "include."

Seeking the most efficient method to load content from a php file into a designated div on my webpage, prioritizing speed, minimal performance requirements, and ease of implementation. Unsure whether it's preferable to utilize php or javascript for t ...

Navigating through the content of slots within recurring slots in a subcomponent in Vue.js

I am encountering an issue with a child component, where each row in an object is rendered inside a div with a specific slot. I need to pass data from the parent for each of these elements. I've been attempting to iterate through every element of the ...

Having trouble utilizing the data obtained from an API, encountering errors such as 'data is undefined' leading to nothing displaying on the screen, or 'data.map() is undefined'

I'm relatively new to working with APIs. Although I have successfully made a post, I am creating a new one to clearly outline my issue. My goal is to retrieve posts from the dummyapi. Below is the code snippet that I am using: import React from &a ...

What is the method for selectively applying a "fade to black" mask to an input field?

For my current project, I need to incorporate a design feature where a "fade to black" mask gradually appears on the left side of an input field once the text content reaches the maximum visible width of the input box. The image below provides a visual re ...

Providing secure access to Apostrophe-CMS S3 assets and attachments via HTTPS

Currently, I am utilizing Amazon S3 to deliver both my static assets and user uploads within the context of apostrophe-cms. While my site is loading via https, all of my assets appear to be loading using http. I have set up a cloudfront distribution at th ...

Unleashing the Power of Node Js: Retrieving File Data and Form Data in POST Requests

When sending form data values using Postman, you can utilize a NodeJS server in the backend to handle the POST request. Here is an example of how to structure your code: require('dotenv').config(); const express = require('express'); co ...

Perform DOM manipulation prior to triggering the AJAX event to prevent CSRF Error

Currently, I am faced with a challenge while working on Django. My goal is to implement a chained AJAX call - meaning that once one call returns, it triggers additional AJAX calls. Despite thorough research and referencing the suggested methods in the Djan ...

Tips for preventing the extraction of resolve from promises and initiating a process before a callback

There is a common pattern I frequently find myself using: const foo = () => { const _resolve; const promise = new Promise(resolve => _resolve = resolve); myAsyncCall(_resolve); return (dataWeDontHaveYet) => promise.then(cb => c ...

Snowflake - JSON parsing error: unexpected character found outside string: '/'

I'm struggling with Snowflake as I try to load JSON data into a table. When attempting to load the JSON file through an external stage using an airflow dag task, I encounter the following error: ERROR - Task copy_raw_data failed to execute job 856 ( ...

Transforming field names in JSON using AngularJS $resource

I am currently working on an AngularJS project that interacts with data through an API. During the implementation of the 'create' functionality using $resource, I encountered a challenge with naming conventions. While I use camelCase, the API onl ...

Organizing items within a group

As I embarked on my journey of creating my first Meteor app, I encountered a challenge that left me feeling a bit lost. I have a collection of Entries and I want to categorize them by date, not simply sort them. Each entry comes with a date and I envision ...

If there is only one item, jCarousel will not display anything

After incorporating jCarousel into jQuery ui Tabs, I created a page which can be found at the following link: The issue arises when clicking on the 3rd tab (containing only one item), as nothing is visible until the left arrow is clicked to navigate back. ...

Leverage Node.js modules to reassign variable values

My simplified JavaScript module simulates an eye pose. var pose = {}; var eye = {}; var left = {}; left.pitchPos = 37; left.yawPos = 47; exports.init = function () { eye.left = left; pose.eye = eye; return this; }; exports.eye = function (e ...

"Utilize Node.js to generate a nested array structure with groupings

Here is an array data that I have: [ { tempId: 1, nik: '11002', employeeName: 'Selly Amaliatama', basic_salary: 3500000, id_component: 'AD0128114156', componentName: 'Tunjangan Maka ...

Choose from a range of knockout fetching options for the select feature and choose one

Upon loading my page, there is a <select> element positioned. I am utilizing knockout data-bind to retrieve the values like this: <select data-bind="attr: { id: 'input-' + id(), required: !allowBlank }, option ...

Create proper GeoJSON responses using Flask and the GeoAlchemy2 application

For the past few days, I have been contemplating how to ensure my Flask application can return accurate GeoJSON data. Here is the progress I have made so far: models.py class Building(base): __tablename__ = 'buildings' id = Column(Inte ...

Does this task require a high amount of CPU resources for Node.js on the back-end?

I am currently developing an Android app and I am faced with a decision on whether to utilize node.js or PHP for the back-end. The task at hand involves users inputting query parameters, such as zip codes, which are then used to perform database queries ...

Casting types of objects in Angular2 using TypeScript

Trying to extract the model object from the JSON obtained through a http response call. The following JSON represents the body of the http response, { "dataType": "RWSupplier", "partyName": "Lifecare Pharmaceuticals", "partyShortName": null, "partySecon ...