I am running into an issue when attempting to access individual fields of objects stored within an array.
I have an array of non-uniform objects, we'll call cache.
var cache = new Array();
The put function allows adding items to the array.
function put(item, value) {
cache[item] = value;
}
An example of usage:
var item_abc = { item_a: 'some value', item_b: 'another value' };
put('ITEM_ABC',item_abc);
The problematic function is called update which updates a field for an item in the array with a new value.
function update(item, field, value) {
cache[item][field] = value;
}
Here is the troublesome code:
update('ITEM_ABC','item_a','a new value');
In the browser, this seems to work fine, but in a "--use_strict" Node.js environment, it runs into issues. I'm assuming this is related to precedence and the way in which multi-dimensional arrays are evaluated versus object fields.
How do I reference a object field without knowing the field name at runtime, when the object itself exists within an array?
Reading from the field in question always returns undefined.
function check(item, field) {
console.log(cache[item][field]);
if (typeof cache[item][field] !== 'undefined')
console.log('field exists');
else
console.log('field undefined');
}
Running:
check('ITEM_ABC','item_a');
Outputs:
undefined
'field undefined'
use strict?typeof cache[item][field]is alwaysundefinedvar cache = {};(JavaScript doesn't have associative arrays.)