Jump to content

Merging two objects/array


cs.punk

Recommended Posts

Hey guys.

 

What I am trying to do is have a page that updates the records every time period (15 seconds?).

 

So it keeps a local 'array' and it downloads the updated 'record list' via ajax (will implement this later).

It then checks which records are missing from local one and updates it if necessary.

 

For now my question is should I be using objects/arrays to store the record list. If object, how do I sort the list?

 

Thank you.

 

<script type='text/javascript'>

var users = {
						1 : ["Jay", 11],
						2 : ["Bob", 12],
						3 : ["Chris", 18]
					  };

var jsonOb = {"users": {
						3 : ["Chris", 18],
						4 : ["Joe", 17],
						5 : ["Jack", 16]
					   }
			 };

for (var i in jsonOb.users)
{
	if (users[i] == null)
	{
		alert ('Added:' + i);
		users[i] = jsonOb.users[i];
	}
}

console.debug(users);
</script>

Link to comment
Share on other sites

You're using them the wrong way round; you should have an array of user objects, not an object of user arrays. I'm assuming the array index is the user ID? If so you should be able to use the concact() method of the array object (everything is an object in JavaScript, even arrays) to merge the two.

 

Edit

 

As for sorting, you could wrap the array within a 'collection' type object, that provides methods for sorting based on an item's property within the collection. As a base to start from:

 

function UserCollection(users)
{
    this.collection = users;

    this.merge = function(more_users)
    {
        this.collection.conact(more_users);
    }

    this.sortBy = function(property)
    {
        // Sort the users by property provided
    }
}

 

You would then instantiate a UserCollection object like so:

 

var collection = new UserCollection(users); // 'users' being your JSON data

// Merge more users
collection.merge(more_users); // 'more_users' being the additional JSON data

 

It's only a basic example, but might help you structure the code better.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.