1

I have an array of objects, I want to remove a few properties of this object, by calling a function and passing the array and the key I want to delete.

I referred this answer on Stack Overflow and it works when I specify the key manually, like id. It deletes the id property of each object in the array.

const newArray = array.map(
            ({
                id,
                ...otherAttributes
            }) => otherAttributes
        );

But when I pass the key to the function, and then use the key from the parameter, it is not able to detect the key in the object and so not able to delete it. The function body is something like this:

removeKeyFromObjectsArray(newArray, key) {           
        const newArray = products.map(
            ({
                key,
                ...otherAttributes
            }) => otherAttributes
        );
        return newArray;

I call this function using this.removeKeyFromObjectsArray(this.updatedProducts, 'id') but the objects inside this array still has the key. (The this is because it's inside a Vue App and I need to refer to a different function in the same instance).

This function works if we manually specify the key name like id but it does not work when we pass the key string through a parameter and then use it, can someone explain what is the issue here and how can I solve it?

Tribunal
  • 130
  • 2
  • 16

2 Answers2

3

To use computed property names in destrcuturing, you need to wrap key with [] and assign it to a new variable (_ in this case). Otherwise, it will destructure a property called "key" from the object and not a property with the value in the key variable

function removeKeyFromObjectsArray(products, key) {
    const newArray = products.map(
      ({
        [key]: _,
        ...otherAttributes
      }) => otherAttributes
    );
    return newArray;
}

console.log(
  removeKeyFromObjectsArray([{ id: 1, name: 'name1'},
                            { id: 2, name: 'name2'}], 'name')
)
adiga
  • 34,372
  • 9
  • 61
  • 83
1

That's removing the literal key - use dynamic property notation with square brackets [] to get the result you want:

const newArray = products.map(({ [key]: _, ...otherAttributes }) => otherAttributes);

The reason I'm assigning the unwanted key to _ above is because it's convention to use _ as an "unwanted" or "ignore this" key. Note that this is different to prefixing the key with _ (_key) which means "don't modify this directly - use getters or setters instead".

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79