-1

My sample data

var data = { "users":[
            {
                "firstName":"Ray",
                "lastName":"Villalobos",
                "joined": [""]

            },
            {
                "firstName":"John",
                "lastName":"Jones",
                "joined": ["Jan","15","2014"]

            }
    ]};

I would like to check if 'joined' node exists, check if it is empty (as in first users element) and if it has value then concatenate them.

Sincerely appreciate any help..

Thanks

Arnab
  • 2,324
  • 6
  • 36
  • 60
  • Where specifically are you stuck? – T.J. Crowder Aug 14 '14 at 07:54
  • "Concatenate" them how? Just the values in each one? All the values in all of them together? – T.J. Crowder Aug 14 '14 at 07:56
  • `if (data["joined"] && data["joined"] !== '') {}` – Alex Aug 14 '14 at 07:59
  • possible duplicate of [Checking if an array key exists in a JavaScript object or array?](http://stackoverflow.com/questions/1098040/checking-if-an-array-key-exists-in-a-javascript-object-or-array) – Alex Aug 14 '14 at 08:00
  • @Alex -Tx, so I should try if ("joined" in data.users)- that should give me whether joined node exists.. what do I do to figure if it has at least one string and not [""] – Arnab Aug 14 '14 at 09:47
  • @T.J.Crowder I would like it concatenated with space seaparation eg. "Jan 15 2014" – Arnab Aug 14 '14 at 09:49

1 Answers1

0

Simply loop through, check that the joined property isn't falsey, and use Array#join.

data.users.forEach(function(user) {
    if (user.joined) {
        user.joined = user.joined.join(" ");
    }
});

forEach is one way of looping through arrays in JavaScript, it was added in ES5. There are a bunch of other ways.

In the above, your first one will get converted from [""] to ""; if that's not what you want, you add more checks:

data.users.forEach(function(user) {
    if (user.joined && (user.joined.length !== 1 || user.joined[0] !== "")) {
        user.joined = user.joined.join(" ");
    }
});
Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875