UNPKG

js-object-utilities

Version:
23 lines (22 loc) 730 B
"use strict"; module.exports = (object, key, value) => { const keyParts = key.split("."); // Protect against prototype pollution if (keyParts.includes("__proto__") || keyParts.includes("constructor")) { // If the key is __proto__ or constructor, return the object and do nothing since this is a security risk. return object; } let objectRef = object; keyParts.forEach((part, index) => { if (keyParts.length - 1 === index) { return; } if (!objectRef[part]) { objectRef[part] = {}; } objectRef = objectRef[part]; }); const finalKey = keyParts[keyParts.length - 1]; objectRef[finalKey] = value; return object; };