I have this code that is supposed to avoid modifying the original data object "info" array of objects but it does! despite it is processing copies of this array?! I need to keep the original data object intact as otherwise, I am getting continually modified data object with each call of the functions as if they are chained together?!
const data = {
owner: "John Doe",
info: [
{
employeeId: 123000456,
firstName: "Alex",
lastName: "Mckenna",
email: "alex@work.org",
salary: 48000,
department: "Art and Media",
},
{
employeeId: 123000777,
firstName: "Devon",
lastName: "Foley",
email: "devon@work.org",
salary: 75000,
department: "Advertising",
},
{
employeeId: 123000894,
firstName: "Riley",
lastName: "Couch",
email: "riley@work.org",
salary: 33000,
department: "Shipping",
},
{
employeeId: 123000533,
firstName: "Cara",
lastName: "Eramchuk",
email: "cara@work.org",
salary: 39000,
department: "Accounting",
},
{
employeeId: 123000721,
firstName: "Cole",
lastName: "Tilbury",
email: "cole@work.org",
salary: 43000,
department: "Accounting",
},
{
employeeId: 123000832,
firstName: "Bree",
lastName: "Northam",
email: "bree@work.org",
salary: 61000,
department: "Shipping",
},
{
employeeId: 123000271,
firstName: "Mark",
lastName: "Miller",
email: "mark@work.org",
salary: 55000,
department: "Sales",
},
{
employeeId: 123000442,
firstName: "Jenna",
lastName: "McEvoy",
email: "jenna@work.org",
salary: 40000,
department: "Sales",
},
],
};
const myCompany = {
renameProp(arr, old, neu) {
const modified = arr.map((obj) => {
if (old in obj) {
obj[neu] = obj[old];
delete obj[old];
return obj;
} else {
return `property, ${old}, doesn't exist for employee ${obj["firstName"]} ${obj["lastName"]}`;
}
});
return modified;
},
sortCopy(arr, prop) {
try {
const copied = Array.from(arr);
copied.sort((a, b) => {
if (typeof a[prop] === "string" && typeof b[prop] === "string") {
if (a[prop].toLowerCase() > b[prop].toLowerCase()) return 1;
else if (b[prop].toLowerCase() > a[prop].toLowerCase()) return -1;
else return 0;
} else {
if (a[prop] > b[prop]) return 1;
else if (b[prop] > a[prop]) return -1;
else return 0;
}
});
return copied;
} catch (err) {
return err.message;
}
},
};
console.log(myCompany.renameProp(data.info, "salary", "wage"));
console.log("\n\n", myCompany.renameProp(data.info, "firstName", "name"));
console.log("\n", "examples of second function: ", "\n");
console.log(
"sorted by employeeId: \n\n",
myCompany.sortCopy(data.info, "employeeId")
);
console.log(
"\n sorted by first name: \n\n",
myCompany.sortCopy(data.info, "firstName")
);
console.log("\n\n original array \n\n", data);