Reputation: 2337
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.
Upvotes: 2
Views: 5920
Reputation: 10849
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.
Upvotes: 7
Reputation: 101
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
Upvotes: 1
Reputation: 1460
You can use #aduch variant or start to use great lib that called underscorejs
_.keys($scope.hi) // result: ["a","b","c"]
Upvotes: 2