The worm The worm - 26 days ago 8
Javascript Question

Iterate through array of objects and print out property value

If I have this:

myArr = [{name: 'rich', secondName: 'james'}, {name: 'brian', secondName: 'chris'}];

mySecondArr = [];


how can I loop over this so that
mySecondArr = ['rich', 'brian']


I was thinking of doing something like:

for (var key in myArr){
if (Object.hasOwnProperty(name){
mySecondArr.push(name[value])
}


I know that is pseudo code but cant quite thing of the syntax for doing this as simply as possible

NO JQUERY PLEASE

Answer

Try this

for (var i=0;i<myArr.length; i++){
    if (myArr[i].name!=undefined){
      mySecondArr.push(myArr[i].name)
}