007DevilsWorkshop
007DevilsWorkshop

Reputation: 33

Increment Object set javascript

I have an object set

var obj = {
 ref01:{
 test:"abc"
},
ref02:{
 test:"xyz"
},
ref03:{
 test:"pqr"
}
}

and I have new object

const test = {
  test:"def"
}

I want to update the object above with increment value of ref Now ref is03 , I want to append like ref04 and increment each time based on existing obj.

var obj = {
 ref01:{
 test:"abc"
},
ref02:{
 test:"xyz"
},
ref03:{
 test:"pqr"
},
ref04:{
 test:"def"
}
}

i tried object.assign but its directly passing the value . obj = object.assign(obj,{ref:test})

So how can i get it ?

Upvotes: 0

Views: 58

Answers (1)

bturner1273
bturner1273

Reputation: 710

I think you want a list: i.e.

const obj = {
    testObjects: [
        {
            test: 'abc'
        },
        ...
    ]
}

then you can just run:

obj.testObjects.push({test: 'xyz'});

OR if this is an API response you can't change the schema of:

//find last index so you can add the ref obj
const getFormattedIndex = (idx) => String(idx).padStart(2, '0');
let i = 1;
while(obj[`ref${getFormattedIndex(i)}`]) {
   i++;
}
//add object with the correct sequential key
obj[`ref${getFormattedIndex(i)}`] = {test: 'xyz'};

or you could be a bad person and use scope-bleed with a ghetto for loop 😇:

//find last index so you can add the ref obj
const getFormattedIndex = (idx) => String(idx).padStart(2, '0');
for (var i = 1; obj[`ref${getFormattedIndex(i)}`]; i++);
//add object with the correct sequential key
obj[`ref${getFormattedIndex(i)}`] = {test: 'xyz'};

Upvotes: 3

Related Questions