最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

How to print key and values from dictionaries enlisted in array, javascript - Stack Overflow

matteradmin13PV0评论

I am having difficulties printing data from dictionaries stored in an array using double for-loop with

var residents = [{name: "Pyrus", room: "32"},{name: "Ash Ketchum", room: "22"}];

function people() {
    for (let i = 0; i < residents.length; i++) {
        for (let j in residents[i]) {
            document.write(j + ": " + residents[j] + "<br>");
        }
    }
};

people();

What I am retrieving is this:

name: undefined 
room: undefined
name: undefined
room: undefined

I can print the key but it seems like it does not fetch value defined to the key! What am I doing wrong?

A success criteria is to print in HTML.

I am having difficulties printing data from dictionaries stored in an array using double for-loop with

var residents = [{name: "Pyrus", room: "32"},{name: "Ash Ketchum", room: "22"}];

function people() {
    for (let i = 0; i < residents.length; i++) {
        for (let j in residents[i]) {
            document.write(j + ": " + residents[j] + "<br>");
        }
    }
};

people();

What I am retrieving is this:

name: undefined 
room: undefined
name: undefined
room: undefined

I can print the key but it seems like it does not fetch value defined to the key! What am I doing wrong?

A success criteria is to print in HTML.

Share Improve this question asked Jul 30, 2018 at 15:49 DisabledWhaleDisabledWhale 8711 gold badge10 silver badges15 bronze badges 1
  • 3 should be residents[i][j] – mhodges Commented Jul 30, 2018 at 15:55
Add a ment  | 

6 Answers 6

Reset to default 2

You have chained two loops together so your function needs to access the parents index then the property that you wish to reference.

function people() {
    for (let i = 0; i < residents.length; i++) {
        for (let j in residents[i]) {
            document.write(j + ": " + residents[i][j] + "<br>");
        }
    }
};

This is the simplest way I think(Use foreach()):

var residents = [{name: "Pyrus", room: "32"},{name: "Ash Ketchum", room: "22"}];

function people() {
    residents.forEach(function(resident) {
 document.write(resident.name + ": " + resident.room + "<br>");
});

}
people();

why not try like this with forEach()

var residents = [{
  name: "Pyrus",
  room: "32"
}, {
  name: "Ash Ketchum",
  room: "22"
}];

function people(residents) {
  residents.forEach((element) => {
    for (var key in element) {
      if (element.hasOwnProperty(key)) {
        console.log(key + ':' + element[key]);
      }
    }
  });

};
people(residents);

You can avoid some of the for loops and make the code a little easier to read using forEach and Object.entries:

var residents = [{name: "Pyrus", room: "32"},{name: "Ash Ketchum", room: "22"}];

residents.forEach(res => {
    Object.entries(res).forEach(([key, value]) => {
    console.log(key + ": " + value ); //subing console.log so it prints here
    //document.write(key + ": " + value + "<br>");
    })
})

Using a regular for-loop it would go like the below code. Also, I strongly remend you to check if all the properties (j) are own properties (with hasOwnProperty), otherwise this will look up in the prototype chain. This can be a problem if the objects are added to the array dynamically, otherwise you can bypass this check.

var residents = [{name:"Pyrus",room:"32"},{name: "Ash Ketchum",room:"22"}];

function people() {
  for (let i = 0; i < residents.length; i++) {
    for (let j in residents[i]) {
      if (residents[i].hasOwnProperty(j)) { // <-- check if it is an own property!
        document.write(j + ": " + residents[i][j] + "<br>");
        //first access the object in residents[i], for example {name: "Pyrus",room: "32"}, then to its properties-values with residents[i][j]
      }
    }
  }
};

people();

You need to access residents[i][j] since you are iterating residents in the first place.

so your code bees :

document.write(j + ": " + residents[i][j] + "<br>");

See this working js fiddle

You could also write it like this :

function people(){
    residents.forEach(r => {
        for(let j in r){
          document.write(j + ": " + r[j] + "<br>");
      }
    })
}

Hope this helps.

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far