cs.punk Posted October 28, 2011 Share Posted October 28, 2011 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> Quote Link to comment https://forums.phpfreaks.com/topic/249974-merging-two-objectsarray/ Share on other sites More sharing options...
Adam Posted October 28, 2011 Share Posted October 28, 2011 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. Quote Link to comment https://forums.phpfreaks.com/topic/249974-merging-two-objectsarray/#findComment-1283018 Share on other sites More sharing options...
Adam Posted October 28, 2011 Share Posted October 28, 2011 Typo in the merge() method - should be "concat(..". Quote Link to comment https://forums.phpfreaks.com/topic/249974-merging-two-objectsarray/#findComment-1283062 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.