选择嵌套数组对象并替换它

时间:2017-01-15 13:18:08

标签: javascript arrays mongodb ecmascript-6

我有一个数组(作为mongoDB查询的结果),有一些这样的元素:

{ 
    "_id": "ExxTDXJSwvRbLdtpg",
    "content": [
        {
            "content": "First paragraph", 
            "language":"en", 
            "timestamp":1483978498 
        },
        {
            "content": "Erster Abschnitt", 
            "language":"de", 
            "timestamp":1483978498 
        }
    ]
}

但我需要为每个数据数组元素只获取一个内容字段,该字段应由语言选择。所以结果应该是(假设选择英语内容):

{ 
    "_id": "ExxTDXJSwvRbLdtpg",
    "content": "First paragraph"
}

而不是获取所有内容数据......

我尝试使用find(c => c.language === 'en),但我不知道如何将其用于数据数组的所有元素。也许它也可以直接作为mongodb查询获取数据??

3 个答案:

答案 0 :(得分:3)

你可以迭代数组并替换里面的值。



var array = [{ _id: "ExxTDXJSwvRbLdtpg", content: [{ content: "First paragraph", language: "en", timestamp: 1483978498 }, { content: "Erster Abschnitt", language: "de", timestamp: 1483978498 }] }];

array.forEach(a => a.content = a.content.find(c => c.language === 'en').content);

console.log(array);




检查content

的版本



var array = [{ _id: "ExxTDXJSwvRbLdtpg", content: [{ content: "First paragraph", language: "en", timestamp: 1483978498 }, { content: "Erster Abschnitt", language: "de", timestamp: 1483978498 }] }, { _id: "no_content" }, { _id: "no_english_translation", content: [{ content: "Premier lot", language: "fr", timestamp: 1483978498 }, { content: "Erster Abschnitt", language: "de", timestamp: 1483978498 }] }];

array.forEach(function (a) {
    var language;
    if (Array.isArray(a.content)) {
        language = a.content.find(c => c.language === 'en');
        if (language) {
            a.content = language.content;
        } else {
            delete a.content;
        }
    }
});

console.log(array);




答案 1 :(得分:3)

鉴于_idlanguage是输入变量,那么您可以使用此aggregate命令来获得预期结果:

db.collection.aggregate([{
  $match: {
    _id: _id,
  }
}, {
  $unwind: '$content'
}, {
  $match: {
    'content.language': language,
  }
}, {
  $project: {
    _id: 1,
    content: '$content.content'
  }
}])

答案 2 :(得分:1)

var aobjs = [{
  "_id": "ExxTDXJSwvRbLdtpg",
  "content": [
    {
      "content": "First paragraph",
      "language":"en",
      "timestamp":1483978498
    },
    {
      "content": "Erster Abschnitt",
      "language":"de",
      "timestamp":1483978498
    }
  ]
}];

var result = aobjs.map(o => ({ id: o._id, content: o.content.find(c => c.language === 'en').content }));

这将返回每个只有id和content的对象。在此示例中,结果将是:

[{id:' ExxTDXJSwvRbLdtpg',内容:'第一段' }]