javascript 从包含对象的数组中获取字段

javascript getting fields from an array with objects

我用这样的对象填充了一个数组,然后用 JSON.stringifty(obj, null, '\t');

打印出来

给我这样的输出:

[
    {
        "title": "here's the title"
    },
    {
        "description": "this is a description"
    }
]

现在我正在尝试从这个包含对象的数组中取回数据。像这样使用 array.map:

var title = objArray.map(function(a) {return a.title;});

当我这样做时:

console.log(title); //the output looks like this
,here's the title,,,

如果我像这样手动进入数组

console.log(results[0]['title']); //the output is well formatted
here's the title

为什么会这样,我怎样才能让 map 函数不将那些额外的逗号添加到我的返回值中?

是的,因为数组中的 2 个元素是:

{
    "title": "here's the title"
}

{
    "description": "this is a description"
}

但它们没有相同的属性: 所以当你试图在第二个元素中显示 属性 title 时,JS 解释器只是 return undefined

它将 return 数组中所有内容的值,因此您将在没有标题的 objects 的结果数组中得到这些空值。不过,您可以在 returning 地图函数中的值之前检查 title 的值。例如:

if (a.title) return a.title;