如何遍历另一个数组对象(JSON)内的数组对象?

时间:2018-10-17 21:01:02

标签: javascript html arrays html5

以下是我从API调用接收的用户列表,该调用从AWS cognito获取用户列表。我希望能够遍历它,以便在网页上显示用户的姓名和电子邮件。我正在尝试result[0].attributes[3]迭代到“ given_name”,结果是对象。 I need the "email", "given_name" and "family_name"

5 个答案:

答案 0 :(得分:1)

您可以使用filter确定是否可以找到对象属性,然后返回该对象。

result[0].Attributes.filter(obj => obj.name === name);

这是一个例子:

let result = [{
  Attributes: [{
      name: "Mario"
    },
    {
      name: "Luigi"
    },
    {
      name: "Toad"
    },
    {
      name: "Peach"
    }
  ]
}]

function lookfor(name) {

  return result[0].Attributes.filter(obj => obj.name === name);
}

console.log(lookfor("Mario"));
console.log(lookfor("Peach"));

答案 1 :(得分:0)

for(var i in array){
   var attr = array[i].Attributes;
   for(var l in attr){
      // attr[l].Name returns name
      // attr[l].Value returns values
   }
}

答案 2 :(得分:0)

您可以使用map迭代数组

arrributes.map(function(arr) => {
  console.log(arr.Name, arr.Value)
})

答案 3 :(得分:0)

Object.keys(result).forEach(key => {
    let resultObject = result[key].map(array => {
      if (array.Name == "given_name") {
        console.log(array.value)
      } else if (array.Name == "email") {
        console.log(array.value);
      }
    });
  });

答案 4 :(得分:0)

const response = [
    { Attributes: [
      {Name: 'given_name', Value: 'name 1'},
      {Name: 'family_name', Value: 'family 1'},
      {Name: 'email', Value: 'email1@gmail.com'}
      ]
    },
    { Attributes: [
      {Name: 'given_name', Value: 'name 2'},
      {Name: 'family_name', Value: 'family 2'},
      {Name: 'email', Value: 'email2@gmail.com'}
      ]
    },
  ];
  
  const users = response.map((ele) => {
      const { Attributes } = ele;
      return Attributes.reduce((agg, {Name, Value}) => {
        if (Name === 'given_name') {
          agg.name = Value;
        }
        if (Name === 'email') {
          agg.email = Value;
        }
        return agg;        
      }, {});      
 });
    
console.log(users);