0

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 ?

5
  • 2
    It is bad practice to have properties with a sequential number as suffix. Don't do this. Arrays were invented for this purpose. Commented Jun 9, 2022 at 14:24
  • Why you don't simply store your data in an array? obj = [{ref: 'abc'}, {ref: 'def'}] So you can use obj.push({ref: 'ghi'}) Commented Jun 9, 2022 at 14:26
  • @trincot just out of curiosity: why is it bad practice? Commented Jun 9, 2022 at 14:29
  • its s response from Api @trincot Commented Jun 9, 2022 at 14:33
  • i want the ref as increment since comes from Api , i need to add new ref incremented and send it back @Yukulélé Commented Jun 9, 2022 at 14:35

1 Answer 1

3

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'};
Sign up to request clarification or add additional context in comments.

3 Comments

How does this run ? @bturner1273
here I'll edit because I see it is an api response now that I assume you can't change
Yes, i need to append into existing object set with new ref increment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.