如何迭代数组中的对象值?

时间:2017-08-30 05:29:26

标签: javascript arrays

我有一个这样的对象:

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

我可以轻松地执行forEach并执行console.log(item)但如果我只想要值cricket,swim,dance,zumba(不需要hobby1到{{1} }})。有人能告诉我如何单独提取价值吗?

4 个答案:

答案 0 :(得分:1)

如果你想要一个只有兴趣爱好的对象,你可以减少数组以返回

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

答案 1 :(得分:1)

试试这个,我理解的是你只需要“爱好”作为价值而不是它们的索引

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);

输出将是

数组[“板球”,“游泳”,“舞蹈”,“尊巴舞”]

答案 2 :(得分:0)

您可以使用for内的for轻松遍历对象和数组,如下所示:



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])
    }
}




答案 3 :(得分:0)

您可以使用array#reduce在数组中累积所有爱好。

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; }