It seems like you're trying to scan through an array, filtering out certain values and possibly navigating through nested arrays within it. The solution lies in recursion. Let's start by understanding how to filter out specific keys from an array:
function omitFromArray(array, valuesToOmit) {
const newArray = [];
for (const value of array) {
if (valuesToOmit.indexOf(value) === -1) {
newArray.push(value);
}
}
return newArray;
}
const arrayToTest = [1, 2, 3, 4, 5, 6];
const testValuesToOmit = [1, 4, 6];
console.log(omitFromArray(arrayToTest, testValuesToOmit));
// returns [2, 3, 5]
While this method works for flat arrays, we need a recursive approach to handle nested arrays efficiently. Here's an example of how that can be achieved:
function omitFromNestedArray(array, valuesToOmit) {
function walk(array, valuesToOmit) {
const newArray = [];
for (const value of array) {
if (Array.isArray(value)) {
newArray.push(walk(value, valuesToOmit));
} else {
if (valuesToOmit.indexOf(value) === -1) {
newArray.push(value);
}
}
}
return newArray;
}
return walk(array, valuesToOmit);
}
const nestedArrayToTest = [1, 2, [3, [4, 5], 6], 7];
const testValuesToOmit = [1, 4, 6];
console.log(omitFromNestedArray(nestedArrayToTest, testValuesToOmit));
// returns [2, [3, [5]], 7]
This recursive function delves into nested arrays, handling each level appropriately until the desired output is obtained. Feel free to ask if you have any questions!
EDIT: To adapt the code for objects instead of arrays, check out this snippet:
function removeUnwantedKeysFromObject(obj, unwantedKeys) {
function walk(obj, unwantedKeys) {
for (const key of Object.keys(obj)) {
const value = obj[key];
if (typeof value === 'object') {
walk(value, unwantedKeys);
}
if (unwantedKeys.indexOf(key) !== -1) {
delete obj[key];
}
}
}
walk(obj, unwantedKeys);
}
let objectToTest = {key1: true, key2: 2, key3: { nested1: 'JavaScript' }};
removeUnwantedKeysFromObject(objectToTest, ['key2', 'key3']);
console.log(objectToTest);
// returns { key1: true }
objectToTest = {key1: true, key2: 2, key3: { nested1: 'JavaScript' }};
removeUnwantedKeysFromObject(objectToTest, ['nested1']);
console.log(objectToTest);
// returns { key1: true, key2: 2, key3: {} }
Keep in mind that this code modifies the original object. If you require a new object, you'll need to adjust the code accordingly or utilize a library for deep cloning.