我有一个类似这样的文档:
{
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"]
}
]
我的初始解决方案是通过Underscore库的_.map
函数运行它(这与我想要删除下划线无关......)然后使用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
函数本身,或者通过某种过滤器链接它但我不知道哪一个是最快的在这种情况下。
答案 0 :(得分:2)
Underscore还附带了一个数组方法compact
,它将从数组中删除所有falsey和null值:
_.compact([0, 1, false, 2, '', null, 3]);
=> [1, 2, 3]
您可以在地图后调用数组上的_.compact(array)
。
答案 1 :(得分:2)
您可以使用reduce:
var listWithoutUnderscores = _.reduce(myList, function(list, val, key) {
if (key.lastIndexOf("_", 0) === -1){
list.push( {fieldName: key, value: val});
}
return list;
}, []);
答案 2 :(得分:1)
您可以使用 pick 并传递谓词来获取有效密钥,然后在这些字段中传递map:
var validKey = function(value, key){
return _.first(key) != '_';
}
var createField = function(value, key){
return {
fieldname: key,
value: value
}
}
var result = _.chain(data)
.pick(validKey)
.map(createField)
.value();
var data = {
name: "Johnny Boy",
age: 24,
hobbies: ["fencing", "chess", "raves"],
_createdAt: '2015-05-15T18:12:26.731Z',
_createdBy: "JohnnyBoy",
_id: 'mQW4G5yEfZtsB6pcN'
}
var validKey = function(value, key){
return _.first(key) != '_';
}
var createField = function(value, key){
return {
fieldname: key,
value: value
}
}
var result = _.chain(data)
.pick(validKey)
.map(createField)
.value();
console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
&#13;