简体   繁体   中英

Map keys to emit function

i've got an object in couchDB and in this looks like are several arrays, im new to couchDB and i don't know how to access the keys of it. The document looks like this:

{
   "_id": "113232",
   "_rev": "1-c967a81c0eccba6a7c92e3c4b352d4eb",
   "name": "Ezequiel Campion",
   "vorlesungen": [
       {
           "Ethik": 1.7
       },
       {
           "Glaube und Wissen": 5
       },
       {
           "Logik": 1.7
       },
       {
           "Bioethik": 1.7
       },
       {
           "Erkenntnistheorie": 1
       },
       {
           "Grundzuege": 4
       },
       {
           "Der Wiener Kreis": 1.7
       }
   ]
}

I just want to have the keys like Ethik, Glaube und Wissen,... not the values to this keys. My actual map functions looks like this:

function(doc) {
    emit(doc.vorlesungen, null);
  }

the output is for example:

[{"Bioethik": 1}]

now i only want the value Bioethik, could anyone tell me how to access it? i've already tried .keys() like usual with JS Arrays and i've also tried to perform a JSON.encode before using keys() but there is no output in this case. I think that it will be just a trivial answer because i don't know the syntax...

regards Eric

after long testing i've found a solution for my problem:

function(doc) {
  var vorl;
  if(doc.vorlesungen){
    for(i=0;i<doc.vorlesungen.length;i++){
      for(vorl in doc.vorlesungen[i]){
        emit(vorl, 1);
      }
    }
  }
}

this shows me the corret output, but i think it's not very pretty cause of the for loops. In college cases like this were solved with foreach loops to iterate the array, but i don't get 'em working. Could anybody show me an example foreach to this case please?

Is this what you are looking for?

 function(doc){
    doc.vorlesungen.forEach(function(item){
        if(typeof(item) === "object"){
          var keys = Object.keys(item);
         keys.forEach(function(key){emit(key)})
        }
    });
}

The code iterates over the array doc.vorlesungen . If the item is an object it gets all the keys of the object. Then for each key so obtained it emits it.

This is the result I get when running the view

{"total_rows":7,"offset":0,"rows":[
{"id":"113232","key":"Bioethik","value":null},
{"id":"113232","key":"Der Wiener Kreis","value":null},
{"id":"113232","key":"Erkenntnistheorie","value":null},
{"id":"113232","key":"Ethik","value":null},
{"id":"113232","key":"Glaube und Wissen","value":null},
{"id":"113232","key":"Grundzuege","value":null},
{"id":"113232","key":"Logik","value":null}
]}

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