我有一个看起来像这样的文档:
{
name: "Johnny Boy",
age: 24,
hobbies: ["fencing", "chess", "raves"],
_createdAt: 2015-05-15T18:12:26.731Z,
_createdBy: "JohnnyBoy",
_id: mQW4G5yEfZtsB6pcN
}
我的目标是返回不以下划线开头的所有内容,并对其格式进行一些不同的调整,因此我将得出以下结论:
[
{
fieldName: "name",
value: "Johnny Boy"
},
{
fieldName: "age",
value: 24
},
{
fieldName: "hobbies",
value: ["fencing", "chess", "raves"]
}
]
我最初的解决方案是通过_.map
Underscore库的功能(与我要专门删除下划线的内容无关...)来运行它,然后lastIndexOf
用来找出哪些键以下划线开头:
var listWithoutUnderscores = _.map(myList, function(val, key) {
if (key.lastIndexOf("_", 0) === -1)
return {fieldName: key, value: val}
return null
})
但是,这实际上将返回,null
而不是_
返回数组中以开头的字段:
[
...
{
fieldname: "hobbies",
value: ["fencing", "chess", "raves"]
},
null,
null,
null
]
我想完全删除它们,最好是在map
函数本身中删除它们,或者通过某种过滤器将其链接起来,但是我不知道在这种情况下哪一个最快。
您可以为此使用reduce:
var listWithoutUnderscores = _.reduce(myList, function(list, val, key) {
if (key.lastIndexOf("_", 0) === -1){
list.push( {fieldName: key, value: val});
}
return list;
}, []);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句