const deepReplace = (data, targetValue, newValue) => {
if (Array.isArray(data)) {
return data.map(item => deepReplace(item, targetValue, newValue));
} else if (typeof data === 'object' && data !== null) {
return Object.fromEntries(
Object.entries(data).map(([key, value]) => [key, deepReplace(value, targetValue, newValue)])
);
} else {
return data === targetValue ? newValue : data;
}
};
// 사용 예시
const obj = {
a: 1,
b: [2, { c: 1, d: [1, 2, 3] }],
e: { f: 1, g: { h: 1 } }
};
const result = deepReplace(obj, 1, 99);
console.log(result);
/*
{
a: 99,
b: [2, { c: 99, d: [99, 2, 3] }],
e: { f: 99, g: { h: 99 } }
}
*/
카테고리 없음
댓글