Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

111
Views
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 ?

about 4 years ago ยท Juan Pablo Isaza
1 answers
Answer question

0

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'};
about 4 years ago ยท Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!