-2

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

The worm
  • 4,618
  • 11
  • 31
  • 48

5 Answers5

1

Try this

for (var i=0;i<myArr.length; i++){
    if (myArr[i].name!=undefined){
      mySecondArr.push(myArr[i].name)
}
M14
  • 1,680
  • 2
  • 14
  • 29
1

You can use map like this :

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

var mySecondArr = myArr.map(x => x.name);
console.log(mySecondArr);
kevin ternet
  • 4,216
  • 2
  • 16
  • 25
0

You can use the map function and return the secondName

var result = myArr.map(function(a) {return a.secondName;});
Sajeetharan
  • 203,447
  • 57
  • 330
  • 376
0

You can use a simple map (ES6 code):

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

var mySecondArr = myArr.map(o => o.name);

console.log(mySecondArr);
trincot
  • 263,463
  • 30
  • 215
  • 251
0

Try following:

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

        var mySecondArr = [];

        myArr.forEach(function (data, index, myArr) {
            debugger;
            mySecondArr.push(data.name);
        });

        alert(mySecondArr);