Intersecting Objects With A Default Object In JavaScript
I have an object with objects, which are basically settings per guild. In these objects are various configuration options that the admin of their guild can change. { '1': { '
Solution 1:
This is a perfect use case for JavaScript's prototypal inheritance:
const defaultObj = {
foo: "Hello, World!",
bar: "Foo example",
roo: {
doo: "boo"
}
};
const obj = Object.assign(Object.create(defaultObj), { foo: "New foo" });
const anotherObj = Object.create(defaultObj);
console.log('obj.foo', obj.foo);
console.log('anotherObj.foo', anotherObj.foo);
console.log('obj.bar', obj.bar);
defaultObj.bar = "New bar";
console.log('obj.bar', obj.bar);
console.log('anotherObj.bar', anotherObj.bar);
defaultObj.foobarexample = "ello";
console.log('obj.foobarexample ', obj.foobarexample );
console.log('anotherObj.foobarexample ', anotherObj.foobarexample );
In this code, all of the objects created from defaultObj
with Object.create
have a reference on defaultObj
. When trying to access a property of the resulting objects, the property will be looked up in the object itself, and then in defaultObj
if not found. defaultObj
can safely be mutated after the objects have been created (it cannot be reassigned though, because the objects created would keep a reference on the previous one).
Solution 2:
https://repl.it/@HenriDe/httpsreplitHenriDeIntersectinobjectswithdefault
this one should work for what you are looking for.
const defaultValues = {
"1" : {
foo: 'Hello, World!',
bar: 'Foo example',
roo: {
doo: 'boo',
newest: {
goal: "dodo"
}
},
hello: "world"
}
};
function eachRecursive(obj, defaultValues, level = 0){
// check each key amongst the defaults
for (var k in defaultValues){
// if our original object does not have key attach it + default values associated
if (!obj.hasOwnProperty(k)) {
obj[k] = checkWith[k]
}
// keep calling as long as value is object
if (typeof obj[k] == "object" && obj[k] !== null)
eachRecursive(obj[k], checkWith[k], level + 1);
}
}
}
// for each of the specific entries check
for (let [key, value] of Object.entries(data)) {
eachRecursive(data[key], defaultValues["1"])
}
console.log(data["1"])
Post a Comment for "Intersecting Objects With A Default Object In JavaScript"