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
  });
});
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
StackThis
  • 883
  • 3
  • 15
  • 45

2 Answers2

2

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) {  ...
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • Thanks for this, it's perfect.. As a follow up, how could I assign `var data` the value of the second object `{ title : 'Two', value : 2, }` using something that involves the 'Two'.. (req.params.`value` purposes, to then pull the respective object) – StackThis Apr 11 '14 at 07:03
  • There's no way to select by value, so you'd have to iterate and check for the value you're looking for, something like this -> http://jsfiddle.net/fdrYx/1/ – adeneo Apr 11 '14 at 07:09
1
var titles = [];
Items.forEach(function(item){
 titles.push(item.title);
});
//now display titles
vivek_nk
  • 1,590
  • 16
  • 27