You can use a filter() call and pass an array of indexes to filter against. This could easily be adapted to also delete by value.
function updateFunction(option, id, prop, value) {
...
if (option == "delete") {
if (prop == "cars") {
ex[id][prop] = ex[id][prop].filter((_, i) => !value.includes(i));
}
}
return ex;
};
updateFunction("delete","list_1","cars", [0, 2, 3])
var ex = {
"list_1": {
"money": 1000,
"manager": "Louis",
"cars": ["mazda", "ford_focus", "fiat", "dacia"]
},
"list_2": {
"money": 300,
"manager": "Keen",
"cars": ["fiat", "dacia"]
}
};
function updateFunction(option, id, prop, value) {
if (option == "update") {
if (prop == "money" && value != "") {
ex[id][prop] = value;
} else if (prop == "manager" && value != "") {
ex[id][prop] = value;
} else if (prop == "cars") {
ex[id][prop].push(value);
}
}
if (option == "delete") {
if (prop == "cars") {
ex[id][prop] = ex[id][prop].filter((_, i) => !value.includes(i));
}
}
return ex;
};
updateFunction("update", "list_1", "manager", "Andrew");
updateFunction("delete","list_1","cars", [0, 2, 3])
console.log(ex)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Adapted to delete by either index or value.
function updateFunction(option, id, prop, value) {
...
if (option == 'delete') {
if (prop == 'cars') {
ex[id][prop] = ex[id][prop].filter((v, i) => !value.filter.includes(value.byValue ? v : i));
}
}
return ex;
};
updateFunction('delete', 'list_1', 'cars', { filter: [0, 2, 3], byValue: false });
updateFunction('delete', 'list_2', 'cars', { filter: ['fiat'], byValue: true });
var ex = {
list_1: {
money: 1000,
manager: 'Louis',
cars: ['mazda', 'ford_focus', 'fiat', 'dacia'],
},
list_2: {
money: 300,
manager: 'Keen',
cars: ['fiat', 'dacia'],
},
};
function updateFunction(option, id, prop, value) {
if (option == 'update') {
if (prop == 'money' && value != '') {
ex[id][prop] = value;
} else if (prop == 'manager' && value != '') {
ex[id][prop] = value;
} else if (prop == 'cars') {
ex[id][prop].push(value);
}
}
if (option == 'delete') {
if (prop == 'cars') {
ex[id][prop] = ex[id][prop].filter((v, i) => !value.filter.includes(value.byValue ? v : i));
}
}
return ex;
}
updateFunction('update', 'list_1', 'manager', 'Andrew');
updateFunction('delete', 'list_1', 'cars', { filter: [0, 2, 3], byValue: false });
updateFunction('delete', 'list_2', 'cars', { filter: ['fiat'], byValue: true });
console.log(ex);
.as-console-wrapper { max-height: 100% !important; top: 0; }