从对象数组构造一个元素数组? [英] Construct an array of elements from an array of objects?

查看:91
本文介绍了从对象数组构造一个元素数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个数据结构如下:

 项目:[
{
标题: '一',
值:1,
},
{
标题:'Two',
值:2,
}
]

如何从项目中构建一个数组的标题?如['One','Two']



如果标题 == [] { ..

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


解决方案

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

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

FIDDLE



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

 如果titles == [] {... 

应该是

  if(titles == []){... 
/ pre>

甚至更好

  if(Array.isArray标题)&& titles.length === 0){... 


With a data structure that looks like this:

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

How would I construct an array of the titles from Items? As in ['One', 'Two']

This codeset generates a 'SyntaxError: Unexpected identifier' if titles == [] {..

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
  });
});

解决方案

I would just use Array.map to return the titles in a new array

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

FIDDLE

Also, the error is due to missing parentheses

if titles == [] {  ...

should be

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

or even better

if (Array.isArray(titles) && titles.length === 0) {  ...

这篇关于从对象数组构造一个元素数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆