-3

I have an object like this:

{
  username: {
    hobby: [
      {
        hobby1: "cricket",
        hobby2: "swim"
      },
      {
        hobby3: "dance",
        hobby4: "zumba"
      }
    ]
  }
}

I can easily do a forEach and do console.log(item) but what if I just want the values cricket,swim,dance,zumba alone (don’t need hobby1 through hobby4). Can someone show me how to extract the values alone?

Ram N
  • 3
  • 1
  • 3

4 Answers4

1

If you want an object with just the hobbies, you can reduce the array to return that

var obj = {
  username: {
    hobby: [{
        hobby1: "cricket",
        hobby2: "swim"
      },
      {
        hobby3: "dance",
        hobby4: "zumba"
      }
    ]
  }
}

var obj2 = obj.username.hobby.reduce((a, b) => {
  Object.entries(b).forEach(x => a[x[0]] = x[1]); return a;
}, {})

console.log(obj2);
console.log(Object.values(obj2)); // just the values
adeneo
  • 312,895
  • 29
  • 395
  • 388
1

Try this, what i understand is that you just need "hobbies" as value not they indexes

var json= {
        username: {
           hobby: [{
               hobby1: "cricket",
               hobby2: "swim"
           },
           {
               hobby3: "dance",
               hobby4: "zumba"
           }]
         }
       }    ;

var hobbies=json.username.hobby;

var hobbies_arr=[];
var i=0;
for(var item in hobbies){
     item=hobbies[item];          
     for(var hobby in item){
         hobby=item[hobby];
         hobbies_arr[i]=hobby;
         i++;
     }
}

console.log(hobbies_arr);

Out put would be

Array [ "cricket", "swim", "dance", "zumba" ]

RashFlash
  • 992
  • 2
  • 20
  • 40
0

You can easily loop through the objects and arrays using a for within a for like this:

let obj = {
      username: {
          hobby: [
              {
                  hobby1: "cricket",
                  hobby2: "swim"
              },
              {
                  hobby3: "dance",
                  hobby4: "zumba"
              }
          ]
     }
}

for(let hobbies of obj.username.hobby) {
    for(let hobby in hobbies) {
          console.log(hobbies[hobby])
    }
}
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
0

You can use array#reduce to accumulate all your hobbies in an array.

var obj = {username: {hobby: [{hobby1: "cricket",hobby2: "swim"},{hobby3: "dance",hobby4: "zumba"}]}};

var result = obj.username.hobby.reduce((res, obj) => res.concat(Object.values(obj)), []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51