Pergunta de entrevista da empresa Fragma Data Systems

Write a function changeKey(obj, oldKey, newKey) that recursively replaces all occurrences of oldKey with newKey in an object or array. Do not change the key if it is "id". let obj = { id: 7373, data: [ { type: "1", id: 73 }, { name: "xyz", type: "23", vas_id: 73, x_data: [{ id: 72, data: { xx_data: { id: 673, a: ["id"] } } }, "id"], }, "abc", "id", 123, { id: { data: 123, id: ["a", "b"] } }, ], };

Resposta da entrevista

Sigiloso

6 de nov. de 2024

let obj = { id: 7373, data: [ { type: "1", id: 73 }, { name: "xyz", type: "23", vas_id: 73, x_data: [{ id: 72, data: { xx_data: { id: 673, a: ["id"] } } }, "id"], }, "abc", "id", 123, { id: { data: 123, id: ["a", "b"] } }, ], }; function changeKey(obj, oldKey, newKey) { if (Array.isArray(obj)) { return obj.map(item => changeKey(item, oldKey, newKey)); } else if (obj !== null && typeof obj === 'object') { const updatedObj = {}; for (let key in obj) { if (key === oldKey) { updatedObj[newKey] = obj[key]; } else { updatedObj[key] = changeKey(obj[key], oldKey, newKey); } } return updatedObj; } return obj; } const updatedObj = changeKey(obj, "id", "newId"); console.log(updatedObj);