0

I've a JavaScript object like this.

var obj = {
    "set1": [1, 2, 3],
    "set2": [4, 5, 6, 7, 8],
    "set3": [9, 10, 11, 12]
};

This JavaScript object will be totally dynamic. So I need to get the key of this JavaScript object using some index method. Like

key[1] should return "set2"

So how can I get the ID of any index from the JavaScript object?

2
  • and the question is? Commented Nov 18, 2015 at 11:33
  • @madalinivascu Please check the edit :) Commented Nov 18, 2015 at 11:45

5 Answers 5

1

try this:

convert the json in a array:

  var obj = {
        "set1": [1, 2, 3],
        "set2": [4, 5, 6, 7, 8],
        "set3": [9, 10, 11, 12]
    };
    var arr = []
    for (var key in obj) {
        arr.push(obj[key]);
    }
    console.log(arr[1]);

or array of objects:

var obj = {
    "set1": [1, 2, 3],
    "set2": [4, 5, 6, 7, 8],
    "set3": [9, 10, 11, 12]
};
var arr = []
for (var key in obj) {
    arr.push({key:obj[key]});
}
console.log(arr[1]);

jsfiddle:https://jsfiddle.net/3yx8a12e/

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

3 Comments

This solution will get messy when dealing with lots of objects. You will get a lot of code repetition.
@Magrangs you create a function then
No need to. The functionality to do this already exists is modern browsers (with one line of code) and for those that don't a polyfill is available.
1

You have these options (here's JSFiddle too):

var obj = {
    "set1": [1, 2, 3],
    "set2": [4, 5, 6, 7, 8],
    "set3": [9, 10, 11, 12]
};

var sets = [];
for (var o in obj) {
  if (obj.hasOwnProperty(o)) { //Thanks Magrangs for reference
     sets.push(o);
  };
};

//Or in modern browsers
//var sets = Object.keys(obj);

console.log(sets[1]);

1 Comment

It is safer to add an hasOwnProperty check before the push. Otherwise it will iterate properties of the prototype chain.
0

You can use Object.keys(obj) to get an array of the keys of the object.

In your example, Object.keys(obj)[1] will return "set2".

Note that Object.keys is not supported in older browsers (see browser compatibility guide below):

  • Chrome - 5
  • Firefox (Gecko) - 4.0 (2.0)
  • Internet Explorer - 9
  • Opera - 12
  • Safari - 5

But you can polyfill it using the following code:

// 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

2 Comments

But I heard ,keys is browser dependent and not all browsers supports it? Is that true?
Yeah, but you can use a polyfill. See the article link. Most modern browsers support it though.
0
function getKey(data, i){
    var n = 0;
    for(var k in data){
        if(n == i) return k;
        n++;
    }
}

data - your js object, i - index of member

Comments

0

You can Retrieve All Keys this code

    var obj = {
        "set1": [1, 2, 3],
        "set2": [4, 5, 6, 7, 8],
        "set3": [9, 10, 11, 12]
    };

var newary= [];
for (var x in obj) {
  if (obj.hasOwnProperty(x)) { //Thanks Magrangs for reference
     newary.push(x);
  };
};

console.log(newary[1])


/*For Modern Browser use this code*/

    // Retrieve All Keys of Object 
    Object.keys(obj);

    // Retrieve Specific Keys of Object
    Object.keys(obj)[1];

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.