Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

This question already has an answer here:

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
  });
});
share|improve this question

marked as duplicate by Felix Kling, zzzzBov, Farid Nouri Neshat, Put12co22mer2, Donal Fellows Apr 13 '14 at 17:13

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1  
Please note that you have a normal JavaScript object, not JSON. Your problem doesn't seem to have anything to do with JSON. – Felix Kling Apr 11 '14 at 6:46
    
@FelixKling appreciate the clarification – StackThis Apr 11 '14 at 6:52
up vote 2 down vote accepted

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) {  ...
share|improve this answer
    
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 7: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 -> jsfiddle.net/fdrYx/1 – adeneo Apr 11 '14 at 7:09
    
Very cool, many thanks – StackThis Apr 11 '14 at 7:17
var titles = [];
Items.forEach(function(item){
 titles.push(item.title);
});
//now display titles
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.