0

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.

1
  • 3
    You just assign the object. myValidation[1] = { id:'331', name:'tom', field1: 'Yes', field2: 'Yes', field3: 'Yes', field4: 'Yes' } Commented Sep 2, 2021 at 9:42

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.