0

I have the following array, I would like to implement a function that will loop through the array, and replaces the names.val = '', except the second item or index[1]. I tried foreach function. but i don't know how to implement it properly

names = [
{
  name: 'first',
  inputType: 'number',
  val: void 5
},
{
  name: 'second',
  inputType: 'number',
  val: void 2
},
{
  name: 'third',
  inputType: 'text',
  val: void 3
},

]

Tried the following

 resetValues() {
 let names = this.names
 names.forEach((names:any, index:number)=>{
  if(index=1){
   names[1] = names[1].val
 } else{
   names = ''
 }
})
}
2
  • 2
    index=1 should be index === 1, and you probably want to use names.val. Reusing the same variable name over and over, shadowing the last, is quite confusing btw. I also don't understand, why you use a different number ever time for void Commented Sep 26, 2019 at 20:54
  • ... and on top you should not do anything for index===1, just do names.val = '' in case of index !== 1 Commented Sep 26, 2019 at 20:57

1 Answer 1

1

My understanding is that you want to change the val property to an empty string using a forEach loop, for every item except index 1:

let names = [
  {
    name: 'first',
    inputType: 'number',
    val: void 5
  },
  {
    name: 'second',
    inputType: 'number',
    val: void 2
  },
  {
    name: 'third',
    inputType: 'text',
    val: void 3
  }
];
console.log('Before', names);

function resetValues()
{
 names.forEach((obj, index)=>
 {
  if(index !== 1)
   {
    obj.val = '';
  } 
 });
}

resetValues();
console.log('After', names);

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.