简体   繁体   中英

How to Iterate through an array object inside another array object (JSON)?

The following is a list of users I receive from an API call that gets the list of users from AWS cognito. I want to be able to iterate through it to display the name and email of the user on a web page. I am trying result[0].attributes[3] to iterate to "given_name", result being the object. 我需要“email”、“given_name”和“family_name”

You can use filter to determine if an object property can be found, and then return that object.

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

Here's an example:

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

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

You can iterate an array using map

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM