Using Variable Keys to Access Values in JavaScript Objects

Accessing an object property with a dynamically-computed name

There are two ways to access properties of an object:

  • Dot notation: something.bar
  • Bracket notation: something['bar']

The value between the brackets can be any expression. Therefore, if the property name is stored in a variable, you have to use bracket notation:

var something = {
bar: 'foo'
};
var foo = 'bar';

// both x = something[foo] and something[foo] = x work as expected
console.log(something[foo]);
console.log(something.bar)

Using variable keys to access values in JavaScript objects

You can access object properties by dot notation or by bracket notation.

var x = {'test': 'hi'};
alert(x.test); // alerts hi
alert(x['test']); // alerts hi

When you have a dynamic value, you have to use the latter:

var property = 'test';
alert(x.property); // looks for x.property, undefined if it doesn't exist
alert(x[property]); // looks for x['test'], alerts hi

So what you actually want is:

alert(data[bsID][0].time);

EDIT:

Not sure what you're doing wrong, but this is working for me on Firebug's console:

var data = {"A5A50000":[{"bsid":"A5A50000","chanCount":17,"time":"2009-05-27 16:36:45","avgInterference":1.711765,"maxInterference":4.97,"avgHandsets":205.1176,"maxHandsets":315,"avgCalls":6.4118,"maxCalls":13,"avgCBA":3868.98059,"maxCBA":7463,"sumSuccessCBA":197318,"sumTimeoutHandoff":133,"sumAttemptHandoff":1028,"sumDeniedHandoff":216,"sumConfirmHandoff":679,"sumHandoffNetwork":61873,"sumJoinNetwork":96888,"sumLeaveNetwork":93754,"sumRcvdKeepalive":98773,"sumTimeoutKeepalive":19748,"sumAttemptUplink":93689,"sumBlockedUplink":62453}]};
var bsID = 'A5A50000';
alert(data[bsID][0].time);

How to use a variable for a key in a JavaScript object literal?

{ thetop : 10 } is a valid object literal. The code will create an object with a property named thetop that has a value of 10. Both the following are the same:

obj = { thetop : 10 };
obj = { "thetop" : 10 };

In ES5 and earlier, you cannot use a variable as a property name inside an object literal. Your only option is to do the following:

var thetop = "top";

// create the object literal
var aniArgs = {};

// Assign the variable property name with a value of 10
aniArgs[thetop] = 10;

// Pass the resulting object to the animate method
<something>.stop().animate(
aniArgs, 10
);

ES6 defines ComputedPropertyName as part of the grammar for object literals, which allows you to write the code like this:

var thetop = "top",
obj = { [thetop]: 10 };

console.log(obj.top); // -> 10

You can use this new syntax in the latest versions of each mainstream browser.

How to access object property by variable in Javascript

You can split the string and loop through it updating a variable refrencing the last found value :

let arr = [  {    title: "hello",    pivot: {      id: 1,      bid: 3    }  },  {    title: "home",    pivot: {      id: 2,      bid: 3    }  },  {    title: "nice",    pivot: {      id: 3,      bid: 3    }  }];
let s = "0.pivot.id";
const getValue = (arr, str) => { let ref = arr; const keys = str.split(".");
keys.forEach(k => { ref = ref[k]; });
return ref;};
const result = getValue(arr, s);
console.log(result);

Access object key using variable in typescript

To compile this code with --noImplicitAny, you need to have some kind of type-checked version of Object.keys(obj) function, type-checked in a sense that it's known to return only the names of properties defined in obj.

There is no such function built-in in TypeScript AFAIK, but you can provide your own:

interface Obj {
a: Function;
b: string;
}

let obj: Obj = {
a: function() { return 'aaa'; },
b: 'bbbb'
};

function typedKeys<T>(o: T): (keyof T)[] {
// type cast should be safe because that's what really Object.keys() does
return Object.keys(o) as (keyof T)[];
}

// type-checked dynamic property access
typedKeys(obj).forEach(k => console.log(obj[k]));

// verify that it's indeed typechecked
typedKeys(obj).forEach(k => {
let a: string = obj[k]; // error TS2322: Type 'string | Function'
// is not assignable to type 'string'.
// Type 'Function' is not assignable to type 'string'.
});

Dynamically access object properties using a variable

Make use of brackets notation for accessing dynamic keys

var my_object = {    object1: {    key: 'value',    key2: 'value2'  },  object2: {    key: 'othervalue',    key2: 'another'  }}
function doSomething(obj_key) { // add a new property to the object my_object[obj_key].new_prop = 'this_new_prop'; // using bracket notation here}
doSomething('object1');
console.dir(my_object);

How to access an object without knowing its name

You could try to use the Object.keys() (also Object.values()) to get keys (or values) of an object without any knowledge of it's data.

Try the following

let data = { 11791146: {m_serverQuery: {name: 'sample'}, m_key: 11791146}};

console.log(Object.keys(data)[0]);

console.log(Object.values(data)[0]);
console.log(Object.values(data)[0].m_serverQuery);
console.log(Object.values(data)[0].m_key);


Related Topics



Leave a reply



Submit