我有以下数组:
[
{ "publication": "" },
{ "publication": [
{ "author": "Author of Paper",
"journal": "Journal of Paper",
"title": "Title of Paper"
},
{ "author": "Author Paper",
"journal": "Journal Paper",
"title": "Title Paper" } ] },
{ "publication": "" }
]
我想丢弃空条目并将所有条目推送到具有以下输出的新数组中
[
1: {
"author": "Author of Paper",
"title": "Title of Paper"
"journal": "Journal of Paper"
},
2: {
"author": "Author of Paper",
"title": "Title of Paper"
"journal": "Journal of Paper"
}
]
我将如何实现?
我尝试了以下操作:
var container = {};
users = users.map(function(obj) {
for(i = 0; i < publications.length; ++i) {
container[i]
= {
"author": obj.author,
"title": obj.title,
"journal": obj.journal,
};
}
答案 0 :(得分:1)
您可以使用reduce。在内部请首先减少该值是否正确,然后再将其添加到最终输出中。
let arr = [{ "publication": "" },{ "publication": [{ "author": "Author of Paper", "journal": "Journal of Paper", "title": "Title of Paper" }, { "author": "Author Paper", "journal": "Journal Paper", "title": "Title Paper" } ] }, { "publication": "" } ]
let output = arr.reduce((op, {publication} ) => {
if(publication){
op.push(...publication)
}
return op
},[])
console.log(output)
答案 1 :(得分:1)
您可以使用即将到来的Array#flatMap
代替虚假的值。
var array = [{ publication: "" }, { publication: [{ author: "Author of Paper", journal: "Journal of Paper", title: "Title of Paper" }, { author: "Author Paper", journal: "Journal Paper", title: "Title Paper" }] }, { publication: "" }],
result = array.flatMap(({ publication }) => publication || []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 2 :(得分:0)
使用reduce的解决方案
[/*....*/].reduce((acc, {publication}) => acc.includes(publication) ? acc : [...acc, publication], [])