Adrin
Adrin

Reputation: 605

minus all Object keys by one

I have object like this:

let obj = {'0': {x:25, y:12}, '1': {x:55, y:6}, '2': {x:44, y:78} ,...}

Now when I delete one of the inside objects(key) delete obj[i]; (based on their x,y) if the deleted inside object be lets say '0', the new object don't have a '0' inside object anymore and it starts from '1' ({'1': {x:55, y:6}, '2': {x:44, y:78} ,...}). and that cause some problems later on.

So How can I fix that? like when the '0' gets deleted minus all keys (after the key that just deleted) by one.

Upvotes: 2

Views: 349

Answers (4)

Mark
Mark

Reputation: 92450

As the comments suggest, you seem to want this object to behave like an array, which suggests you should just use an array:

[{x:25, y:12}, {x:55, y:6}, {x:44, y:78}]

However, if you must use this, you can quickly take the values as an array, splice() the element out, and spread back to an array. You need to be a little careful because objects don't guarantee order of their elements (another reason to use an array in the first place).

let obj = {'0': {x:25, y:12}, '1': {x:55, y:6}, '2': {x:44, y:78} }

let arr = Object.keys(obj).sort().map(k => obj[k]) // this will preserve order
arr.splice(1, 1)
obj = {...arr}

console.log(obj)

Upvotes: 1

fedeghe
fedeghe

Reputation: 1318

what about a function to delete the element?

let obj1 = {'0': {x:25, y:12}, '1': {x:55, y:6}, '2': {x:44, y:78}};
function del(o, index) {
    let ret = {}, j = 0;
    for (let i in o){
        if (o.hasOwnProperty(i) && ~~i != ~~index){
            ret[j++] = o[i]
        }
    }
    return ret;
}
let obj2 = del(obj1, 1);

Upvotes: 0

Manasi
Manasi

Reputation: 765

You can delete the object you want and then move the data to new object,

    let obj = {'0': {x:25, y:12}, '1': {x:55, y:6}, '2': {x:44, y:78} }

    console.log("Before Delete");
    console.log(obj)
var deleteIndex =1;
    delete obj[deleteIndex];
    var obj2={};
    for (var k in obj){
      if (obj.hasOwnProperty(k)) {
           if(k > deleteIndex){
            obj2[k-1] =obj[k];
        }else{
            obj2[k] =obj[k];
        }
      }
    }
    obj=obj2;
        
    console.log("After Delete");
    console.log(obj);

Upvotes: 1

user3094755
user3094755

Reputation: 1641

obj[i] has gone becase you have deleted it ! If you want to set it to some other value the use...obj[i] = { x: 0, y: 0 } this creates a new object in place of the old one.

Or use an Array...

let obj = [ {x:25, y:12}, {x:55, y:6},{x:44, y:78} ,... ]

then

obj.splice(0,1)

and you have...

[ {x:55, y:6},{x:44, y:78} ,.. ]

with...

obj[0] is {x:55, y:6}

Upvotes: 0

Related Questions