在键值对中,如何打印出非空值 JavaScript



所以在这样的例子中,我试图打印出"信息"中没有null的名称

let files = [
{
name: 'untitled',
information: null
},
{
name: 'folder'
information: 'has storage'
},
{
name: 'new folder',
information: 'has 42 items'
},

我一直在尝试使用的代码是这个,但当我试图打印出没有空的文件夹的名称时,它不起作用

let info = files.filter((a) => {
if (a.information !== null )
return a
});

console.log(info)

当我放入console.log(info.length)以查看它是否真的在接收时,有多少项目中没有null。它确实计算了项目,但当我试图查看是否可以打印出它们的名称时,它只打印undefined

有别的办法吗?

filter返回一个数组,如果要打印名称,则需要再次迭代数组

let files = [{
name: 'untitled',
information: null
},
{
name: 'folder',
information: 'has storage'
},
{
name: 'new folder',
information: 'has 42 items'
}
]
let info = files.filter((a) => {
return a.information !== null;
}).forEach(function(item) {
console.log(item.name)
})

如果您只想要文件夹的名称。使用地图提取,如下所示:

let files = [{
name: 'untitled',
information: null
},
{
name: 'folder',
information: 'has storage'
},
{
name: 'new folder',
information: 'has 42 items'
}
]
let info = files.filter((a) => {
return a.information !== null;
}).map((item)=> {
// Get only the names of the folder
return item.name;
});
console.log(info);

如果有帮助,请尝试以下代码。

let files = [
{
name: 'untitled',
information: null
},
{
name: 'folder'
information: 'has storage'
},
{
name: 'new folder',
information: 'has 42 items'
};
var getFilesWithInfo = function () {
var array = [];
for(var i=0; i<files.length;i++){
if(files[i].information){
array.push(files[i]
}
return array;
}
}
console.log(getFilesWithInfo());

您可以使用filter和map通过两个简单的步骤来实现这一点。

const files = [{
name: 'untitled',
information: null
},
{
name: 'folder',
information: 'has storage'
},
{
name: 'new folder',
information: 'has 42 items'
}
];
const fileNames = files
.filter(f => f.information !== null)
.map(f => f.name);
console.log(fileNames);

最新更新