Using AngularJS to generate an array of keys from a JSON object

Looking to work with a JSON in the following structure:

$data.hello=[{
"x":5,
"y":false,
"z":"amazing"
}];

Desire to extract just the keys and create an array like

$result=["x","y","z"];

Though this might seem simple, it would greatly assist me.

Answer №1

Here is the solution you've been searching for:

Object.keys($scope.hi[0]);

If you're targeting IE, this method will only work in versions 9 and above.

Another approach could be to retrieve them using a loop:

var obj = $scope.hi[0],
    array = [];

for (key in obj) {
   if (obj.hasOwnProperty(key)) {
       array.push(key);
   }
}

Keep in mind that the order of the keys may vary depending on the browser's implementation.

Answer №2

If you're looking for a different approach, consider using the #aduch method or exploring the capabilities of a fantastic library known as underscorejs

_.keys($scope.hi) // output: ["a","b","c"]

Answer №3

As mentioned by @aduch, you can utilize the following code snippet:

Object.keys($scope.hi[0]).

To ensure compatibility with browsers that do not support Object.keys, add the code below before using it:

// Script obtained from: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
if (!Object.keys) {
  Object.keys = (function () {
    'use strict';
    var hasOwnProperty = Object.prototype.hasOwnProperty,
        hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
        dontEnums = [
          'toString',
          'toLocaleString',
          'valueOf',
          'hasOwnProperty',
          'isPrototypeOf',
          'propertyIsEnumerable',
          'constructor'
        ],
        dontEnumsLength = dontEnums.length;

    return function (obj) {
      if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
        throw new TypeError('Object.keys called on non-object');
      }

      var result = [], prop, i;

      for (prop in obj) {
        if (hasOwnProperty.call(obj, prop)) {
          result.push(prop);
        }
      }

      if (hasDontEnumBug) {
        for (i = 0; i < dontEnumsLength; i++) {
          if (hasOwnProperty.call(obj, dontEnums[i])) {
            result.push(dontEnums[i]);
          }
        }
      }
      return result;
    };
  }());
}

More information available here.

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

Offspring maintain a certain position within the larger framework of their parent on a

When resizing the parent wrap container, how can I ensure that the pin (red dot) on the image maintains its relative position? To see the issue, resize the wrap container. #wrap{ position: absolute; width: 100%; height: 100%; top: 0; l ...

Is there a way to display "no results" on the page when the search field is empty, yet still render new results asynchronously while searching?

I am implementing a feature where buttons are dynamically rendered on the page based on user input. Each time the user types a letter, a new set of buttons is displayed on the page using an obj.content that contains the string being typed. Although this fu ...

Unsuccessful conversion of JSON data to HTML using json2html in Python

I have been experimenting with converting JSON data to HTML using json2html. The JSON data structure I am working with is as follows: json_obj = [{"Agent Status": "status1", "Last backup": "", "hostId": 1234567, "hostfqdn": "test1.example.com", "username" ...

Launch a modal by clicking a button located in a separate component using Vue JS

I am dealing with 2 components: TestSearchTool and TestModal. My goal is to display the Modal when a button in the TestSearchTool component is clicked. These two components are siblings in the hierarchy, so I am struggling to pass values between them (even ...

Angular 2 component stays static despite changes in route parameters

So, I am in need of a way to refresh my component after the URL parameter's id has been altered. The following code is from my player.component.ts: import {Component, OnInit, AfterViewInit} from '@angular/core'; import {ActivatedRoute, Rout ...

Fetch and showcase JSON data from a URL on a webpage

I am completely new to JSON and have limited knowledge of Java, JSON, or Ajax. I managed to convert data from a Google Sheets spreadsheet into a JSON URL () and here is the result https://i.sstatic.net/78HKZ.jpg. Now, my goal is to display this data as sho ...

Assign the value in the text box to the PHP session variable

Currently, I am developing a PHP "interactive text game" as a part of my assignment project. My task involves creating a user interface where users input information (such as character names) into text boxes that appear sequentially as they complete the p ...

Asynchronously running a function in AngularJS

My controller passes execution to a factory -- controller.getCustomerById -> factory.getCustomerByID. The factory function is posting and retrieving data via MVC/angular.$http.post, which works fine, but the subsequent actions in my controller function ...

Caching in computer architecture involves organizing data into cache lines and determining

Scope Explore research on enhancing cache efficiency, particularly regarding cache line association in loops. The current inquiry is centered around an array consisting of 1024 integers. Specifications include a CPU cache size of 64k, cache line size of ...

Is there a way to retrieve multiple results by utilizing fetch and randomuser.me?

I am currently working with the randomuser.me API and have set up the fetch request correctly. My goal is to retrieve 5 users separated by commas instead of just one. As mentioned in randomuser.me's documentation, I simply need to append the fetch UR ...

Issue encountered when deploying a Web API using Entity Framework

After successfully creating a Web Api using Entity Framework in Visual Studio 2015 and linking it to a database, I encountered an issue when trying to publish the Api using the Web Deploy method. When accessing the following URL: http://localhost/books/api ...

When you click on an inner div, it triggers a click event on the outer div as well

In my code, I have an outer div labeled paragraph and two inner divs named word. Additionally, there is a unique audio functionality in JavaScript that I obtained from a previous Stack Overflow post: <div class="paragraph" onclick="playSound('this ...

The parameter did not successfully transfer to the internal function within Firebase Cloud Functions

I am currently working on a Firebase cloud function that looks like this: exports.foo = functions.database .ref("/candidates/{jobTrack}/{candidateId}") .onCreate((snap, context) => { const candidate = snap.val().candidate; const jobTrack = ...

Array volatility - ensuring memory coherence of the elements

Consider this code snippet: class A { private Map<String, Object> taskMap = new HashMap<>(); private volatile Object[] tasksArray; // assume this occurs on thread1 public void assignTasks() { synchronized(taskMap){ ...

live PHP recording of data moving between tables

As a beginner, I am working on a project to organize groups of people on the screen using PHP code. I have managed to list Distribution Lists, Member Lists, and People, but I lack experience in this area. Can anyone provide some guidance on how to proceed? ...

When an array is received, a v-for loop is utilized to showcase the outcomes on numerous <select></select> elements. Clicking on one option will modify the values of all other options simultaneously

<select v-model="selectedRole" @change="handleChangeRole"> <option value="" disabled>Select role</option> <option :value="role.id" v-for="role in arrayRoles" :key="role.id">{{ role.title }}</option ...

default folder location for core modules adjustment

While experimenting with module imports in TypeScript, I encountered an issue when trying to import a module using import { Component, OnInit } from '@angular/core';. The compiler was successfully finding the module in the node_modules folder. I ...

Why are my files in the public directory returning a 404 error?

My current file structure is organized as follows: ng |---- controllers | |----homeController.js |---- modules.js node-modules |---- various modules here... public |---- css | |---main.css |---- js | | ...

Retrieving currentUser data using Vue.js, Vuex, Express, and MongoDB

I am currently working on creating a MEVN stack authentication page that displays information about the user who is logged in. After successfully logging in, the router redirects to Home.vue and passes the username as a prop. The onSubmit method in Login. ...

Switching classes will not alter the current class

Having an issue with using toggleClass in jQuery. Check out the code snippet below: $(".guzik").click(function() { $("#third").toggleClass('.pillar-animation-two'); }); function test(){ document.getElementById(&apos ...