UNPKG

json-keypath

Version:

Get and Set values in JSON objects using keypaths

50 lines (45 loc) 995 B
'use strict'; function setValue (object, key, val, strict) { if (object instanceof Object && typeof key === 'string') { var a = key.split('.'); var n = a.length - 1; for (var i = 0; i < n; i += 1) { var k = a[i]; if (k in object) { object = object[k]; } else { if (strict === true) { throw new Error('Invalid path'); } else { object[k] = {}; object = object[k]; } } } object[a[n]] = val; } else { throw new Error('Invalid arguments'); } } function getValue (object, key, strict) { if (object instanceof Object && typeof key === 'string') { var a = key.split('.'); for (var i = 0; i < a.length; i++ ) { var k = a[i]; if (k in object) { object = object[k]; } else { if (strict === true) { throw new Error('Invalid path'); } else { return undefined; } } } return object; } } module.exports = { getValue: getValue, setValue: setValue };