简体   繁体   中英

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

You could reduce the keys with the object.

 var object = { id: 1, id1: 2, id2: 3 }, contentIds = ['id1', 'id2', 'id3'], result = contentIds.reduce((o, k) => ({ [k]: _, ...r } = o, r), object); console.log(result); 

const myObj = { id1: 'test', id2: 'test', id3: 'test' }
const idsToFilter = ['id1', 'id2']
const { id1, id2, ...filtered } = myObj
console.log(filtered)

However you can't do that programmatically unless you know the exact ids you want to filter from the object however. if you want to do it based on an array of ids instead, you'd need to use something like this

function filterObjectByKeys (object, keysToFilter) {
  return Object.keys(object).reduce((accum, key) => {
    if (!keysToFilter.includes(key)) {
      return { ...accum, [key]: object[key] }
    } else {
      return accum
    }
  }, {})
}

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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM