-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
  • 5,580
  • 14
  • 36
  • 49

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,780
  • 2
  • 14
  • 31
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,514
  • 2
  • 19
  • 27
0

You can use the map function and return the secondName

var result = myArr.map(function(a) {return a.secondName;});
Sajeetharan
  • 216,225
  • 63
  • 350
  • 396
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
  • 317,000
  • 35
  • 244
  • 286
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);