We know javascript array.push appends elements to the array. Is there an option to replace the elements in the array? The below function gets called twice and I have no control over event.mediaCollection.mediaIds. So mediaDTOs array gets populated with same number of mediaIds twice. I wish to prevent that from happening.I'm looking to add new mediaIds everytime this function is called instead of pushing mediaIds to the same array.
function calledTwice(){
var mediaIds = event.mediaCollection.mediaIds;
var mediaDTOs = [];
for(var i = 0; i < mediaIds.length; i++) {
mediaDTOs.push({id:mediaIds[i]});
}
}
Edit: Can't afford to create a temporary object to achieve this. Got to get the ids in the mediaDTOs array to be unique.
-
Does mediaDTO's NEED to be an array?doogle– doogle2012年01月20日 00:53:57 +00:00Commented Jan 20, 2012 at 0:53
-
Sorry for not being really clear, but xpapad has almost got what I was looking for. mediaDTOs needs to be an array, I'm not really understanding what difference an object would make?neelmeg– neelmeg2012年01月20日 01:28:52 +00:00Commented Jan 20, 2012 at 1:28
2 Answers 2
change
mediaDTOs.push({id:mediaIds[i]});
to
mediaDTOs[i] = {id:mediaIds[i]};
but since mediaDTOs is local, I am not sure what the problem is...
Comments
Use an object instead:
var mediaDTOs = { };
for(var i = 0; i < mediaIds.length; i++) {
mediaDTOs[ mediaIds[i] ] = true;
}
Then you can get the unique ids with something like:
var ids = [];
for(var id in obj){
ids.push(id);
}
Make sure you really want to make mediaDTOs local though...