简体   繁体   中英

delete property with sequential index in object

i have an object like below:

item = {
  0: 'A',
  1: 'B',
  2: 'C',
  3: 'D'
}

For eg, if i would like to delete '1' from the item object and after it was deleted, '2' and '3' should auto minus 1 and become object below:

item = {
  0: 'A',
  1: 'C',
  2: 'D'
}

Is it possible to achieve this with object beside using array?

Omit the key you don't want, convert to array using Object.values() , and then convert back to object by spreading to an empty object:

 const item = { 0: 'A', 1: 'B', 2: 'C', 3: 'D' } const result = { ...Object.values(_.omit(item, 1)) } console.log(result) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script> 

Or you can create a function that uses rest params:

 const fn = (key, { [key]: _, ...rest }) => ({ ...Object.values(rest) }) const item = { 0: 'A', 1: 'B', 2: 'C', 3: 'D' } const result = fn(1, item) console.log(result) 

使用删除语句

delete item["1"];

You can use an array for removing and for re-indexing purpose.

 let item = { 0: 'A', 1: 'B', 2: 'C', 3: 'D' }; // get values as an array let arr = Object.values(item); // remove element at index 1 arr.splice(1, 1); // extract array to an object item = { ...arr }; console.log(item); 

Here another solution in case you don't want to rely in third party plugins. Lodash is quite a heavy library as well.

var deleteObj = ({data, index}) => {
    var objSize = Object.keys(data).length
    if (index > objSize -1) return data
    var count = index;
    delete data[count];
    count = count+1;
   while (count < objSize){
      data[count-1] = data[count];
      count = count+1;
  }
  delete data[count-1];
  return data;
}

deleteObj({data: {0: "A", 1: "B", 2: "C", 3: "D", 4: "E", 5: "F"}, index: 0});

Or else you can use lodash's filter directly on object (actually you can) to remove unnecessery items and then produce an array in one step, and then just use object spread operator to build back the resultant object.

Example:

 let o = {"0":"A","1":"B","2":"C","3":"D"}, res = {..._.filter(o, (v, k) => k!=1)}; console.log(res); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script> 

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