ArthurJ
ArthurJ

Reputation: 839

Replacing a whole object within a specific array index with another object

I have the following javascript object:

const myValidation = [
   {
       id:'1', name:'qqq', field1: 'Yes', field2: 'No', field3: 'Yes'
   }, 
   {
       id:'330', name:'www', field1: 'Yes', field2: 'Yes'
   }, 
   {
       id:'45', name:'eee', field1: 'Yes' 
   }
]

Based on some condition within my code and if it's true, I want to replace myValidation[1] index object with the following object and it will always be at array index 1:

const newObj = {
           id:'331', name:'tom', field1: 'Yes', field2: 'Yes', field3: 'Yes', field4: 'Yes'
      }

So after replacing the object, myValidation array now looks like:

const myValidation = [
   {
       id:'1', name:'qqq', field1: 'Yes', field2: 'No', field3: 'Yes'
   }, 
   {
       id:'331', name:'tom', field1: 'Yes', field2: 'Yes', field3: 'Yes', field4: 'Yes'
   }, 
   {
       id:'45', name:'eee', field1: 'Yes' 
   }
]

Please note that I don't want to match on ids or any other key, I purely want to replace an object with another object at myValidation[1] index.

Unsure how to achieve this.

Upvotes: 0

Views: 120

Answers (1)

DragonInTraining
DragonInTraining

Reputation: 385

In your case it's very simple, just access the object in your array and set it to the object that you want.

myValidation[1] = { key:'value', key2:'value2'....}

If you ever get to a point where you need to do this without knowing it's the specifically the object in the array at index 1, you could use map and find to achieve this aswell.

Upvotes: 1

Related Questions