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"
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"
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]]
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 Symbol
s) and returns an array of their names.
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.
Here a valid response : https://stackoverflow.com/a/6268840/5013024
use Object.keys