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
https://forums.phpfreaks.com/topic/249974-merging-two-objectsarray/
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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.