How To Use Object Destructuring Spread Operator To Delete Multiple Object Properties
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
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
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);
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM