简体   繁体   中英

How do i loop through the properties of each object in the array, the properties are different in each object. This is Javascript

const team =
[ Manager {
    name: 'Chase Lipscomb',
    position: 'Manager',
    id: '5',
    email: 'something@gmail.com',
    office: '15a' },

  Enginner {
    name: 'David Sierra',
    position: 'Engineer',
    id: '6',
    email: 'somethingelse@gmail.com',
    git: 'davidsiearaa' },

  Intern {
    name: 'Joe Dion',
    position: 'Intern',
    id: '7',
    email: 'sometincool@gmail.com',
    school: 'UCI' } ]

The array is named team. This is the output of the program which I am going to generate an html document for. For each person(object in array) I want to create a card which will show their name, position, id number, and email. And depending on their position also add school for Intern, github for engineer, office number for manager. How can access the properties without having to specify them by name. For example, instead of team.manager.name I want to do something like team[0].key(0).

To be able to refer to the team object, you need to iterate through it twice, once for each team member and the second time for each member's data.

Take note that I have edited your team object.

const team = [{
    Manager: {
    name: 'Chase Lipscomb',
    position: 'Manager',
    id: '5',
    email: 'something@gmail.com',
    office: '15a' },

    Enginner: {
    name: 'David Sierra',
    position: 'Engineer',
    id: '6',
    email: 'somethingelse@gmail.com',
    git: 'davidsiearaa' },

    Intern: {
    name: 'Joe Dion',
    position: 'Intern',
    id: '7',
    email: 'sometincool@gmail.com',
    school: 'UCI' } 
}]
    for (var all in team) {
        var members = team[all]; // object containing all team members
        for (var position in members) {
            var singleMember = members[position];
            console.log(position); // Manager, Engineer, Intern etc
            for (var detail in singleMember) {
                console.log(detail + " = " + singleMember[detail]);
                // name = Chase Lipscomb
                // position = Manager ...
            }
        }
    }

If your goal is to iterate through array and access every element key, then this is the appropriate code.

 const team = [ { name: 'Chase Lipscomb', position: 'Manager', id: '5', email: 'something@gmail.com', office: '15a' }, { name: 'David Sierra', position: 'Engineer', id: '6', email: 'somethingelse@gmail.com', git: 'davidsiearaa' }, { name: 'Joe Dion', position: 'Intern', id: '7', email: 'sometincool@gmail.com', school: 'UCI' } ]; team.forEach(member => { Object.keys(member).forEach(key => { console.log(member[key]); //some other stuff }); });

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