replace-in-object
v2.2.0
Published
Replace nested values in an object, immutably and type safe.
Downloads
2
Readme
Replaces values in objects in a type safe and immutable way.
(Type safety only for TypeScript developers)
const deepObject = {
foo: {
bar: {
hello: "there",
},
array: [
"how",
"abou",
"this",
],
},
cool: "stuff",
};
const replaced = replace(deepObject)
.foo.bar.hello.with("world")
.foo.array[1].with("about")
.foo.array.push("?")
.done();
const typingExample: {
[key: string]: string;
} = {
"hello": "world",
};
// this shorthand is neat when you want to replace a single value (but it works in all cases)
const added = replace(typingExample).newkey.with("This works too")();
const smart = replace(typingExample).hello.update(s => s.toUpperCase())();
const partial = {
some: {
thing: "needs",
to: "change",
},
};
const merged = replace(partial).some.mergeWith({ to: "new!" })();
expect(replaced.foo.array).toStrictEqual(["how", "about", "this", "?"]);
expect(replaced.foo.bar.hello).toBe("world");
expect(added.newkey).toBe("This works too");
expect(smart.hello).toBe("WORLD");
expect(merged.some.to).toBe("new!");