Couchdb 尝试按数组值分组

Couchdb trying to group by array value

我在转换数组时遇到问题。 下面是一个示例输入:

            {
          "_id": "beaconlog_888ff29df356c803_Amsterda",
          "_rev": "5152-3c6e5f47d6860179cf80b9bca3efba4b",
          "beacon_identifier": "Amsterdam",
          "beacon": "office",
          "in_region": true
        }

我用这个映射函数在 couchdb 中创建了一个视图:

        function (doc) {
          if(doc.beacon) {
            emit([doc.beacon_identifier, doc.beacon, doc.in_region],1);

          }
        }     

为了减少我在 group_level 3

上使用 _count

这是我当前的输出:

输出:

{
            "rows": [{
                "key": ["Amsterdam", "office", false],
                "value": 2
            }, {
                "key": ["Amsterdam", "office", true],
                "value": 1
            }, {
                "key": ["Rotterdam", "office", false],
                "value": 1
            }]
        }

这就是我想要实现的最终结果集:

{
    "Amsterdam": {
        "inactive": 2,
        "active": 1
    },
    "Rotterdam": {
        "inactive": 1
    }
}

有人可以帮我解决这个问题吗?

o.rows.reduce(function(result, input) {
  var bool = input.key[2];
  var city = input.key[0];
  result[city] = result[city] || {};
  result[city][bool] = input.value;
  return result;
}, {});

两种解决方案都很简单javascript。

第一个解决方案以您的原始数据集为特色并遍历元素并通过向 属性 添加属性并添加一些值(如果给定)来获取所需的对象。

var array = [{
        "_id": "beaconlog_888ff29df356c803_Amsterda",
        "_rev": "5152-3c6e5f47d6860179cf80b9bca3efba4b",
        "beacon_identifier": "Amsterdam",
        "beacon": "office",
        "in_region": true
    }],
    result = {};

array.forEach(function (a) {
    var TYPE = ['inactive', 'active'];
    result[a.beacon_identifier] = result[a.beacon_identifier] || {};
    result[a.beacon_identifier][TYPE[+a.in_region]] = (result[a.beacon_identifier][TYPE[+a.in_region]] || 0) + 1;
});

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

第二种解决方案采用您上面提到的 输出 并构建一个具有您想要的规范的对象。

var object = { "rows": [{ "key": ["Amsterdam", "office", false], "value": 2 }, { "key": ["Amsterdam", "office", true], "value": 1 }, { "key": ["Rotterdam", "office", false], "value": 1 }] },
    result = {};

object.rows.forEach(function (a) {
    var TYPE = ['inactive', 'active'];
    result[a.key[0]] = result[a.key[0]] || {};
    result[a.key[0]][TYPE[+a.key[2]]] = a.value;
});

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');