2

I have a json in the following structure:

$scope.hi=[{
"a":1,
"b":true,
"c":"great"
}];

I want to extract only the keys and make an array like

$scope.bye=["a","b","c"];

Though seems to be a very basic question but would be very helpful for me.

3 Answers 3

7

This is what you need

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

This only works in IE9+ if you target IE.

An alternative might be to do fetch them with a loop

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

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

Also note that the order of the keys may not be respected depending on the browser implementation.

Sign up to request clarification or add additional context in comments.

2 Comments

Keep in mind that Object.keys does not exist in IE <= 8 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
@aduch: knew about this but needed a generalized solution which works in older browsers also if available.
2

You can use #aduch variant or start to use great lib that called underscorejs

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

2 Comments

It doesn't seems appropriate to use a library for a single assignment.
it make sense to use this lib in your project as it really flexible.
1

Just as @aduch said, use

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

Add the following code before making use of it to handle browsers that do not implement Object.keys

// 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;
    };
  }());
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.