Skip to content

Instantly share code, notes, and snippets.

@mainnika
Created March 30, 2017 14:48
Show Gist options
  • Save mainnika/e2f9229080ae29b4f325fbb7d247f9fa to your computer and use it in GitHub Desktop.
Save mainnika/e2f9229080ae29b4f325fbb7d247f9fa to your computer and use it in GitHub Desktop.
iterable modifier
'use strict';
const util = require('util');
const dump = (obj) => console.log.call(null, util.inspect(obj));
const change = (obj, path, newValue) => {
const iterable = path
.split('.')
[Symbol.iterator]();
for (let iter = iterable.next(), modifier = null; obj !== undefined; iter = iterable.next()) {
if (!iter.done) {
modifier = ((obj) => (value) => obj[iter.value] = value)(obj);
obj = obj[iter.value]
continue;
}
modifier(newValue);
return true;
}
return false;
}
const example = {
foo: {
bar: {
value: 1,
},
},
};
dump(example);
change(example, 'foo.bar.value', 2);
dump(example);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment