I’m using an object’s keys and values to populate other objects like so:
var default_columns = {
column_a: 'value_a',
column_b: 'value_b',
column_c: 'value_c'
// [...]
}
var new_object = {};
for (var key in default_columns) {
new_object[key] = default_columns[key];
}
But then later on in my program, I would like to resuse those keys as parameters. I could do something like this: new_object['column_a'] but if I change 'column_a' in default_columns I need to update it everywhere in the code.
I thought about defining my object like so:
var default_columns = {
a: { k: 'column_a', v: 'value_a' },
b: { k: 'column_b', v: 'value_b' },
c: { k: 'column_c', v: 'value_c' }
}
and iterate through it as follows:
var new_object = {};
for (var key in default_columns) {
new_object[default_columns[key].k] = default_columns[key].v;
}
which would also allow me to use the keys as parameters ( new_object[default_columns.a.k] ) while giving me the opportunity to change the keys (e.g. 'column_a' to 'my_column_a') in default_columns without having to update the code.
Is there a more readable way of doing what I’m trying to achieve with the 2nd approach?
It seems to me that prototypical inheritance is what you want. Instead of copying all properties from
default_columnstonew_objectwithObject.extend, let them inherit from each other (Object.create)!You then can overwrite some columns on the
new_object, which will shadow the inherited properties.Although when your aim is to easily rename the properties, I’d go with the second approach. Renaming on a normal objects means two lines of code: copy to new and delete old. With a set of objects used everywhere you’d just have to change the “key” property of the objects, and it will reflect to everywhere this particular object is referenced.
Note that your iteration to create a new object won’t reflect the changes, as
kandvare dereferenced.