Ad

How To Use Object Destructuring Spread Operator To Delete Multiple Object Properties

- 1 answer

I am using in my reducers Map/Associative array to store object via string ID.

When I need new item into Map I am using this construction

rows: { ...state.rows, [row.id]: row }

When I need delete item form map by Id I am using this.

const  { [rowId]: deleted, ...rows } = state.rows;

Than in variable rows I have map and property with name rowId is missing.

I am wondering how can i do this if i have multiple Ids in array and I need delete all of them via ... operator and destructuring.

const contentIds = ['id1','id2','id3']

// something like ???
const {...[ids], ...rows} 

Yes I can write lamda for that or use omit lodash. But just interesting if it is possible.

Thanks very much

Ad

Answer

I am wander how can i do this if i have multiple Ids in array and I need delete all of them via ... operator and destructuring.

No you can't do this, you're probably getting confused with rest and spread syntax, ... on the left hand side of assignment is rest syntax not spread

Rest and Spread

And rest syntax expects ... followed by variable name, what you're trying is syntaxError

const object = {a:1,b:2,c:3}
const a = ['a','b']
const {...[a], ...rows} = object

console.log(rows)

More over you can't use , tralling comma after rest so even if you do

let {...a, ...rows } = obj 

it's still invalid

const object = {a:1,b:2,c:3}

const {...a, ...rows} = object

console.log(rows)

You can use the solution suggested by @nina or you can create a copy of object and loop through contentIds and delete key/value from copyObj to get desired value

const object = { id: 1, id1: 2, id2: 3 };
const contentIds = ['id1', 'id2', 'id3'];
const objCopy = object

contentIds.forEach(key=>{
  delete objCopy[key]
})

console.log(objCopy);

Ad
source: stackoverflow.com
Ad