Question

I've got an object that looks like this:

message = {
    date: "12-12-12"                                    
    time: "12:05:10",                                   
    name: "Wence",                              
    message: "hey man how are u doing?"
}

Now, I want to create a new object which will look like this:

var messages = {"Wence":["hey man how are u doing?","Thanks. I'm fine too.", "are you up for a game of pokémon?"], "Bas":["Hey! Doing fine. How about you?","sure"]}

After doing so, I need to loop trough the object and filter on message by person. I need to be able to show for instance if "Wence" or "Bas" sent any pictures in their message (the value in the array is 1 message). I guess this is the best way to do so, but I'm open for any suggestions.

Any help is much appriciated.

Was it helpful?

Solution 2

Try this function:

function getMessagesByPerson(obj) {
    var data = {}, item;
    for (var i = 0; i < obj.length; i++) {
         item = obj[i];

         if (!data.hasOwnProperty(item.name)) {
        data[obj.name] = [];
        }

         data[obj.name].push(obj.message);
    }
    return data;
}

This will return exactly your wanted output.

OTHER TIPS

You'd first want to create an empty object to serve as a table:

var messages = {} //creates a new empty object

You'll than have to initialize the list for each user:

messages["Wence"] = [] //initialize Wence's messages to an empty list.

And then, when you need to, you can add to this list - as you would to any list:

messages["Wence"].push("how are you?")

And, when you need to, you can loop through it. If you'd want to loop through each user's messages, you'd want to have a nested loop like this:

for(var username in messages){
   for(var i=0, len = messages[username].length; i<len; i++){
       var msg = messages[username][i]
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top