Skip to content

Instantly share code, notes, and snippets.

@davidalekna
Last active January 6, 2020 11:20
Show Gist options
  • Save davidalekna/10f5a23037b730f1d2c7e1a1ab89a2f4 to your computer and use it in GitHub Desktop.
Save davidalekna/10f5a23037b730f1d2c7e1a1ab89a2f4 to your computer and use it in GitHub Desktop.
Transform nested object string and array values with preferred values without mutation
const example = {
name: "hello_world",
children: {
name: "hello_world_2",
something: "hello_world_2",
children: {
someNumberValue: 23213,
name: "hey______whatsup",
children: {
name: "h_e_ll_o_world_2",
something: "h____ello_world_2",
arrayOfThings: [
"asjd__asdasd",
"dqwndiuwqd_213213",
213213,
[
"asjd__asdasd",
"dqwndiuwqd_213213",
213213,
[
"asjd__asdasd",
"dqwndiuwqd_213213",
213213,
[
"asjd__asdasd",
"dqwndiuwqd_213213",
213213,
{ name: "abu_gelis", children: { name: "kobra______11" } }
]
]
]
]
}
}
}
};
function transform(obj: object, match: RegExp | string, replaceWith: string) {
if (!obj) return;
return Object.keys(obj).reduce((acc, key) => {
const item = obj[key];
if (Array.isArray(item)) {
return {
...acc,
[key]: item.map(i => {
if (Array.isArray(i)) {
return transform(i, match, replaceWith);
}
if (typeof i === "string") {
return i.replace(match, replaceWith);
}
return i;
})
};
}
if (typeof item !== "object") {
let value = item;
switch (typeof item) {
case "string":
value = item.replace(match, replaceWith);
break;
default:
value = item;
break;
}
return {
...acc,
[key]: value
};
}
return {
...acc,
[key]: transform(item, match, replaceWith)
};
}, {});
}
console.log(transform(example, /\_/g, "-"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment