How do I display the array programmatically?

The following script will display the content in < pre id=“display”>< /pre> in the body. The disadvantage of this is that you must list a separate '\nKitty 1: ’ + JSON.stringify(result.rows[X].doc) + for each line. How can the results ti displayed programmatically so it cycles through all the results?

<script type="text/javascript">
/*
Code from: 
http://bl.ocks.org/nolanlawson/038a45134341f3b7235b
*/
PouchDB.destroy('kittens').then(function () {
  return new PouchDB('kittens');
}).then(function (db) {

  db.bulkDocs([
    {
      _id: 'mittens',
      occupation: 'kitten',
      cuteness: 9.0
    },
    {
      _id: 'katie',
      occupation: 'kitten',
      cuteness: 7.0
    },
    {
      _id: 'felix',
      occupation: 'kitten',
      cuteness: 8.0
    }
  ]).then(function () {
    return db.allDocs({include_docs: true});
  }).then(function (result) {
    var display = document.getElementById('display');
    display.innerHTML = 'We put some kitties!' +
      '\nKitty 1: ' + JSON.stringify(result.rows[0].doc) +
      '\nKitty 2: ' + JSON.stringify(result.rows[1].doc) +
      '\nKitty 3: ' + JSON.stringify(result.rows[2].doc);
  }).catch(function (err) {
    console.log(err);
  });

});

</script>

The above script will output:

We put some kitties!
Kitty 1: {"occupation":"kitten","cuteness":8,"_id":"felix","_rev":"1-9dbaece36a3e24d2df93a83735518be0"}
Kitty 2: {"occupation":"kitten","cuteness":7,"_id":"katie","_rev":"1-e363a6a12b4ac68d152db5a1c1d3f25c"}
Kitty 3: {"occupation":"kitten","cuteness":9,"_id":"mittens","_rev":"1-3eee3875d9c5218135a469dc4d40fc40"}

This does not work. The screen is blank. Console says, TypeError: Cannot read property ‘1’ of undefined {stack: (…), message: “Cannot read property ‘1’ of undefined”}

  ]).then(function () {
    return db.allDocs({include_docs: true});
  }).then(function (result) {
  	var out = '';
	var i = 1;
	result.rows.forEach(function(result){
		out += JSON.stringify(result.rows[i].doc) + '<br>';
	});
	document.getElementById('display').innerHTML= out;
	if (i < 3) { i++; }
  }).catch(function (err) {
    console.log(err); // console error here
  });

I found the answer. Change one line to the following:

result.rows.forEach(function(){

Instead of

result.rows.forEach(function(results){

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.