Key Path Update

node v12.22.12
version: 1.0.0
endpointsharetweet
function update(target, updates) { if (typeof updates === "function") return updates(target); const changes = Object .entries(updates) .map(([key, value]) => [key, update(target[key], value)]); return Array.isArray(target) ? changes.reduce((array, [key, value]) => (array[key] = value, array), [...target]) : { ...target, ...Object.fromEntries(changes) }; }
const f = x => x + 1; const g = x => x + 2; const r = x => x + 3; const updated = update({ key1: { key2: 5, key3: 6 }, key4: 7 }, { key1: { key2: previous => f(previous), key3: previous => g(previous) }, key4: previous => r(previous) });
update({ key1: [5, 6], key4: 7 }, { key1: { 0: previous => f(previous), 1: previous => g(previous) }, key4: previous => r(previous) });
Loading…

no comments

    sign in to comment