-1

Is there a way of getting the key from an standard/json object without having to use a for loop?

e.g.

var $Object = {"Key":"Value"};
getKeyAsString($Object["Key"]); //return str "Key"
Connor Simpson
  • 487
  • 1
  • 7
  • 27

4 Answers4

1

Assuming a single object

var $Object = {Key : "Value"};

To get key, use:

Object.keys($Object)[0]

To get Value, use:

$Object[Object.keys($Object)[0]]
Njuguna Mureithi
  • 3,506
  • 1
  • 21
  • 41
0

Well, there will be a loop, but it doesn't have to be in your code:

var obj = { key: "value" };
var k = Object.keys(obj)[0];
console.log(k);      // "key"
console.log(obj[k]); // "value"

Object.keys finds all of the own enumerable properties of the object (the ones named by strings, not Symbols) and returns an array of their names.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Wouldn't

var $Object = { key: 'value1', 'key-1': 'value of key-1'};
  
console.log($Object.key);
console.log($Object['key']);
               
console.log($Object['key-1']);

do it? If the object (only arrays) is not associative. you can access it using index starting from 0.

Adam Azad
  • 11,171
  • 5
  • 29
  • 70
0

Here a valid response : https://stackoverflow.com/a/6268840/5013024

use Object.keys

Community
  • 1
  • 1