I think youâre overcomplicating the overall task a lot here, but this stuff is hard, so to focus on the function youâve written:
So you have a function that takes an object and an array of strings (allowed keys). Youâve called that âallowedâ so Iâll change the name as testObj
is very confusing here:
function comparator (inputObj, allowed) {
let excluded = [];
You iterate over the keys of the input object, in your example that gives you ["item1", "item2", "item3"]
. If the key is not in allowedKeys
, push it to the excluded
array:
Object.keys(inputObj).forEach(function(item){
if (allowed.indexOf(item) == -1) {
excluded.push(item)
for some reason you return
here, this isnât how forEach
works (itâs for side effects) but it wonât do anything at all so no harm done
return excluded; //--> [ 'item2' ]
}
});
So now you have an array called excluded
which has âitem2â in it. And you try to destructure the input object. Which looks like {item1, item2, item3}
. It doesnât have a key called excluded
, so you canât extract that. And you canât assign it to a variable called excluded
, because youâve already used that. And the second part doesnât make sense, because itâs all the properties from filteredObj
, and you canât assign those that way
const {excluded, ...filteredObj} = inputObj;
This is equivalent to writing
const excluded = inputObj.excluded; // this does not exist
const ...filteredObj = inputObj; // this is not valid syntax at all, so cannot work
As both of these variable names have already been declared, this blows up.
Destructuring means you can extract items from an object and assign them to variables in one operation.
const myObj = {foo: 1, bar: 2 }
const { foo, bar} = myObj;
This is exactly equivalent to writing
const myObj = {foo: 1, bar: 2 }
const foo = myObj.foo;
const bar = myObj.bar;
It doesnât do any special filtering or anything, it is just a very useful shorthand. You are assigning to variables, which is why you get the error
Identifier 'excluded' has already been declared
Because youâre trying to repeatedly declare variables with the same name, which you canât do