-1

In JavaScript, how can I push an object to an array, along with some other new property. For example, I want to do something like this:

for(var i=0; i<T_ARRAY.length; i++)
{
   if(!T_ARRAY[i].isCorrect)
   {
      NEW_ARRAY.push({T_ARRAY[i], 'idxPerg' : i+1});
   }    
}
1

2 Answers 2

1

You could simply add the property by doing something like this:

for(var i=0; i<T_ARRAY.length; i++)
{
   if(!T_ARRAY[i].isCorrect)
   {
       var newObj = T_ARRAY[i];
       newObj.idxPerg = i+1;
       NEW_ARRAY.push(newObj);
   }    
}

Also you can use the dynamic key notation

for(var i=0; i<T_ARRAY.length; i++)
{
   if(!T_ARRAY[i].isCorrect)
   {
       var newObj = T_ARRAY[i];
       newObj["idxPerg"] = i+1;
       NEW_ARRAY.push(newObj);
   }    
}
Sign up to request clarification or add additional context in comments.

Comments

1

JavaScript does not have any syntax which adds a property to an object and returns the original object. You have to do it in two statements.

T_ARRAY[i].idxPerg = i+1;
NEW_ARRAY.push(T_ARRAY[i]);

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.