从对象数组构造元素数组

Construct an array of elements from an array of objects?

本文关键字:数组 元素 对象      更新时间:2023-09-26

具有如下数据结构:

Items : [
    {
        title : 'One',
        value : 1,
    },
    {
        title : 'Two',
        value : 2,
    }
]

如何从Items构建一个标题数组?如在[一个,两个]中

如果标题==[]{..,此代码集将生成"SyntaxError:意外标识符"

app.get('/', function(req, res){
    var titles = [];
    for (var i=0, length=Items.length; i < length; i++) {
        if titles == [] {
            titles += Items[i]['title'];
        }
        else {
            titles = titles + ', ' + Items[i]['title'];
        }
        console.log(titles);
    };
  res.render('items', {
    itemTitles: titles
  });
});

我只需要使用Array.map来返回新数组中的标题

var titles = Items.map(function(o) {
    return o.title;
});

FIDDLE

此外,错误是由于缺少括号

if titles == [] {  ...

应该是

if (titles == []) {  ...

甚至更好的

if (Array.isArray(titles) && titles.length === 0) {  ...
var titles = [];
Items.forEach(function(item){
 titles.push(item.title);
});
//now display titles