Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Object Manipulation Object
function getByPath(object, path) {
var keys = path.replace('[', '.').replace(']', '').split('.');
var last = keys.length - 1;
var obj = object;
for (var i = 0; i < last; i++) {
var prop = keys[i];
if (!obj[prop]) return undefined;
obj = obj[prop];
}
return obj[keys[last]];
}
function setByPath(object, path, value) {
var keys = path.replace('[', '.').replace(']', '').split('.');
var last = keys.length - 1;
var obj = object;
for (var i = 0; i < last; i++) {
var prop = keys[i];
if (!obj[prop]) obj[prop] = {};
obj = obj[prop];
}
obj[keys[last]] = value;
return object;
}
// Examples
/*
var snack = {
id: '0',
name: 'Cake',
batters: {
batter: [{
id: '0',
type: 'Regular'
}, {
id: '1',
type: 'Chocolate'
}, {
id: '2',
type: 'Blueberry'
}]
},
hello: []
};
*/
/*
console.log(getByPath(snack, 'id')); // --> '0'
console.log(getByPath(snack, 'batters.batter').length); // --> '3'
console.log(getByPath(snack, 'batters.batter.2.id')); // --> '2'
console.log(getByPath(snack, 'batters.batter[1].id')); // --> '1'
*/
/*
setByPath(snack, 'id', 1); // --> 1
setByPath(snack, 'batters.batter.2.id', 2); // --> 2
setByPath(snack, 'batters.batter[1].id', 1); // --> 1
setByPath(snack, 'hello.0', 'world'); // --> 'world'
setByPath(snack, 'foo.bar', 'new'); // --> 'new'
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.