sort an object based on value in js - javascript

I want to sort an object which is associative in terms (key, value)
I am able to store the values according to the key, but unable to sort them on the basis of value using in-built sort() functions as in case of associative array.
var usernames = {};
username[1] = "ZNAME";
username[2] = "BNAME";
username[3] = "ANAME";
username[4] = "TNAME";
username[5] = "KNAME";
username[5] = "YNAME";
$.each(usernames,function(key, value){
alert(key + " : " + value);
})
Please tell the method to sort with my updated JSFIIDLE
DEMO

You can't sort an object, you have to make it an array. For example:
var usernamesArray = [
{key:1,username:"ZNAME"},
{key:2,username:"BNAME"},
...
{key:5,username:"YNAME"}
];
var sortedUsernamesArray=usernamesArray.sort(function(a,b){
//
return (a.username>b.username)?1:-1;
});
Live demo: http://jsfiddle.net/GrD4v/
Note: jQuery is not needed here.
[Edit] There are a couple different ways to build the usernamesArray. A simple one:
var usernamesObject = {};
var usernamesArray = [];
usernamesObject[1] = "ZNAME";
usernamesObject[2] = "BNAME";
usernamesObject[3] = "ANAME";
usernamesObject[4] = "TNAME";
usernamesObject[5] = "KNAME";
usernamesObject[6] = "YNAME";
for (var i=1;i<7,i++) {
usernamesArray.push({key:i,username:usernamesObject[i]});
}

var username = [];
username[0] = "ZNAME";
username[1] = "BNAME";
username[2] = "ANAME";
username[3] = "TNAME";
username[4] = "KNAME";
username[5] = "YNAME";
username.sort();
$.each(username,function(key, value){
alert(key + " : " + value);
})

Related

Calling an array item into another array

I faced the following functions (or method I don't what is right name of the ):
function getRowArray($scope, object, i){
i = i + 1;
var item = {};
var data = [];
var id = -1;
if ($scope.selectedType !== undefined) {
id = $scope.selectedType.id;
}
var rating = getRating($scope, object, id);
item['name'] = $scope.objectInfo[object]['name'];
item['objectId'] = rating.objectId;
item['hideRating'] = parseInt($scope.objectInfo[object].hideControls) & 1;
item['addInfo'] = rating.addInfo;
item['rating'] = rating.value;
item['ratingId'] = rating.id;
for (var i in $scope.objectInfo[object].childs) {
if ($scope.objectInfo[object].childs[i] == object){
continue;
}
data.push(getRowArray($scope, $scope.objectInfo[object].childs[i], i));
}
item['data'] = data;
return item;
}
and
function getTypeRow($scope, oobject, otype){
var item = {};
var data = [];
var rating = getRating($scope, oobject.id, otype.id);
item['name'] = otype.name;
item['objectId'] = rating.objectId;
item['typeId'] = rating.typeId;
item['ratingId'] = rating.id;
item['addInfo'] = rating.addInfo;
item['rating'] = rating.value;
// item['hideRating'] = parseInt($scope.objectInfo[object].hideControls);
return item;
}
I want to use the hideRating item from the first one in the second, I tried and added the commented line but I got an error it says the object is undifined, is it wrong like that or am I missing something ? thanks in advance
object is undefined because it wasn't initialized; it's not specified in the parameter list for the function getTypeRow. The oobject in the parameter list should be corrected to object:
// Correct 'oobject' to 'object'
function getTypeRow($scope, object, otype){
var item = {};
var data = [];
// Correct 'oobject' to 'object'
var rating = getRating($scope, oobject.id, otype.id);
...
}

How can I iterate through this object in js?

I'm trying to go through the object of rooms[room] and save all the names with a property side = 1 to one array and names with side = 2 to a different array.
Such as:
side1['tom','bob'];
side2['billy','joe'];
this is what I have so far, it's getting the sides but how do I get the names as well?
var room = '1';
var rooms = {};
rooms[room] = {};
var player = 'tom'
rooms[room][player] = {};
rooms[room][player]['side'] = 1;
var player = 'billy'
rooms[room][player] = {};
rooms[room][player]['side'] = 2;
var player = 'joe'
rooms[room][player] = {};
rooms[room][player]['side'] = 2;
var player = 'bob'
rooms[room][player] = {};
rooms[room][player]['side'] = 1;
for (var key in rooms[room]) {
if (rooms[room].hasOwnProperty(key)) {
var obj = rooms[room][key];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
console.log(prop + " = " + obj[prop]);
}
}
}
}
In the code you have, the player names are stored in the variable key during your iterations. Try:
// ...
if (obj.hasOwnProperty(prop)) {
console.log(prop + " = " + obj[prop]);
console.log(key); // <- you get the names
}
But IMHO, your code will soon get very messy when you want to have more players. I would suggest having a function that takes care of creating the players and add them to the arrays you want to create during this process. That way you don't have to iterate over the rooms to build the mentioned arrays side1 and side2.
I would suggest something like this:
var rooms = {};
function newPlayer(roomID, player, side) {
if ( !rooms.hasOwnProperty(roomID) ) {
rooms[roomID] = {};
}
rooms[roomID][player] = {};
rooms[roomID][player].side = side;
if ( !rooms[roomID].hasOwnProperty('side' + side) ) {
rooms[roomID]['side' + side] = [];
}
rooms[roomID]['side' + side].push(player);
}
newPlayer(1, 'tom', 1);
newPlayer(1, 'billy', 2);
newPlayer(1, 'joe', 2);
newPlayer(1, 'bob', 1);
console.log(rooms);

Javascript array change value recursively

I'm stucking at changing an value of an array with unknown depth.
I want to iterate over it and change specific values, after all changes are done I want to receive the whole array back with the applied changes.
Code sample:
var array = [];
array.name = "Page";
array.inside = [];
array.inside.name = "Page inside";
array.inside.inside = [];
array.inside.inside.name = "Page inside inside";
array.inside.inside.inside = [];
function changeValue(array) {
for (var ii in array) {
if (typeof array[ii] === 'object') changeValue(array[ii]);
if (array.name) {
array.name = array.name + " changed";
}
console.log(array);
}
}
changeValue(array);
Try this:
var array = [];
array.name = "Page";
array.inside = [];
array.inside.name = "Page inside";
array.inside.inside = [];
array.inside.inside.name = "Page inside inside";
array.inside.inside.inside = [];
function changeValue(array) {
if (array.name) {
array.name = array.name + " changed";
}
console.log(array);
for (var ii in array) {
if (typeof array[ii] === 'object') changeValue(array[ii]);
}
}
changeValue(array);
Every time through the loop you are changing array.name. That is why you're results have ' changed changed'. Take the array.name modification out of the loop and it works just as expected.
Good luck.

Update JSON values with associated key

I am trying to collect the unique json data, I mean if the key exists the update its value. But not succeed to update the value of existing key.
var fpr_data = [{"rfr_id":"7","user_id":"5","fp_id":"10","raw_id":"3","raw_qty":"20.00","raw_wastage":"2","raw_name":"Buttons"},
{"rfr_id":"9","user_id":"5","fp_id":"10","raw_id":"4","raw_qty":"500.00","raw_wastage":"0","raw_name":"Yarn"},
{"rfr_id":"8","user_id":"5","fp_id":"10","raw_id":"5","raw_qty":"2.00","raw_wastage":"1","raw_name":"Needle"},
{"rfr_id":"7","user_id":"5","fp_id":"10","raw_id":"3","raw_qty":"20.00","raw_wastage":"2","raw_name":"Buttons"}];
var qty = 2, coll={}, _qty=0.00,_wastage=0.00;
// Filter and modify JSON data
$.each(fpr_data, function(i, data) {
_qty = data.raw_qty * qty;
_wastage = data.raw_wastage * qty;
// Next time add on existing keys
if( coll[data.raw_id] == data.raw_id ) {
var q = coll[data.raw_id].qty + _qty;
var w = coll[data.raw_id].wastage + _wastage;
coll[data.raw_id] = {"qty":q, "wastage":w};
}
else {
coll[data.raw_id] = {"qty":_qty, "wastage":_wastage};
}
});
console.log(coll);
In fpr_data there is raw_id that i want to collect unique ids and if the raw_id found in object then update its qty and wastage with raw_qty and raw_wastage. I got Unique JSON data but quantity and wastage are not getting update. What wrong i have done? You can find the same codes in fiddle and check the result in console.
Expected: The value of qty in 3 should be 80
JSFIDDLE
Below condition will not give you correct comparison, when object already exists in array.
if( coll[data.raw_id] == data.raw_id ) {
I think you should just do:
if(coll[data.raw_id]) {
If I understand you correctly try this example
if(coll[data.raw_id]) {
var q = coll[data.raw_id].qty + _qty;
var w = coll[data.raw_id].wastage + _wastage;
coll[data.raw_id] = {"qty":q, "wastage":w};
}
else {
coll[data.raw_id] = {"qty":_qty, "wastage":_wastage};
}
You use jQuery, so enjoy the jQuery.extend() function :
var fpr_data = [{"rfr_id":"7","user_id":"5","fp_id":"10","raw_id":"3","raw_qty":"20.00","raw_wastage":"2","raw_name":"Buttons"},{"rfr_id":"9","user_id":"5","fp_id":"10","raw_id":"4","raw_qty":"500.00","raw_wastage":"0","raw_name":"Yarn"},{"rfr_id":"8","user_id":"5","fp_id":"10","raw_id":"5","raw_qty":"2.00","raw_wastage":"1","raw_name":"Needle"}, {"rfr_id":"7","user_id":"5","fp_id":"10","raw_id":"3","raw_qty":"20.00","raw_wastage":"2","raw_name":"Buttons"}];
console.log(fpr_data);
var qty = 2, coll={}, _qty=0.00,_wastage=0.00;
// Filter and modify JSON data
$.each(fpr_data, function(i, data) {
_qty = data.raw_qty * qty;
_wastage = data.raw_wastage * qty;
// Next time add on existing keys
var currentObj = coll[data.raw_id]; // Try not to repeat yourself ;-)
if( currentObj == data.raw_id ) {
var q = currentObj.qty + _qty;
var w = currentObj.wastage + _wastage;
console.log(data);
coll[data.raw_id] = $.extend(data, {"qty":q, "wastage":w});
}
else {
coll[data.raw_id] = $.extend(data, {"qty":_qty, "wastage":_wastage});
}
});
console.log(coll);
I hope this is what you were looking for.

Javascript | Objects, Arrays and functions

may be you can help me. How can I create global object and function that return object values by id?
Example:
var chat = {
data : {
friends: {}
}
}
....
/*
JSON DATA RETURNED:
{"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
*/
onSuccess: function(f){
chat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends.push(f.users[i])
}
}
How can I create a new function (It will return values by friend_id)?
get_data_by_id: function (what, friend_id) {
/*obj.what = getfrom_globalobject(chat.data.friends???)*/
}
Example of use:
var friend_name = get_data_by_id(name, 62);
var friend_username = get_data_by_id(username, 62);
var friend_avatar = get_data_by_id(thumb, 62);
Try:
get_data_by_id: function (what, friend_id) {
return chat.data.friends[friend_id][what];
}
... but use it like:
var friend_name = get_data_by_id('name', 62);
...and set up the mapping with:
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i];
}
You cannot .push() to an object. Objects are key => value mappings, so you need to use char.data.friends[somekey] = f.users[i];
If you really just want a list with numeric keys, make x5fastchat.data.friends an array: x5fastchat.data.friends = [];
However, since you want to be able to access the elements by friend_id, do the following:
onSuccess: function(f){
x5fastchat.data.friends = {};
for(var i=0; i< f.users.length;i++){
chat.data.friends[f.users[i].friend_id] = f.users[i]
}
}
get_data_by_id: function (what, friend_id) {
obj[what] = chat.data.friends[friend_id][what];
}
Note the obj[what] instead of your original obj.what: When writing obj.what, what is handled like a string, so it's equal to obj['what'] - but since it's a function argument you want obj[what].
Take a look at the following code. You can simply copy paste it into an HTML file and open it. click "go" and you should see the result. let me know if I did not understand you correctly. :
<script>
myObj = { "field1" : { "key1a" : "value1a" }, "field2" : "value2" }
function go()
{
findField(myObj, ["field2"])
findField(myObj, ["field1","key1a"])
}
function findField( obj, fields)
{
var myVal = obj;
for ( var i in fields )
{
myVal = myVal[fields[i]]
}
alert("your value is [" + myVal + "]");
}
</script>
<button onclick="go()">Go</button>
I would recommend using the friend objects rather than getting them by id and name.
DATA = {"users": [{"friend_id":"62","name":"name","username":"admin","thumb":"images/avatar/thumb_7d41870512afee28d91.jpg","status":"HI4","isonline":""},{"friend_id":"66","name":"Another name","username":"regi","thumb":"images/avatar/thumb_d3fcc14e41c3a77aa712ae54.jpg","status":"Всем привет!","isonline":"avtbsl0a6dcelkq2bd578u1qt6"},{"friend_id":"2679","name":"My name","username":"Another","thumb":"images/avatar/thumb_41effb41eb1f969230.jpg","status":"","isonline":""}]}
// simple data store definition
Store = {items:{}};
NewStore = function(items){
var store = Object.create(Store);
store.items = items || {};
return store
};
Store.put = function(id, item){this.items[id] = item;};
Store.get = function(id){ return this.items[id]; };
Store.remove = function(id){ delete this.items[id]; };
Store.clear = function(){ this.items = {}; };
// example
var chat = {
data : {
friends : NewStore()
}
}
// after data loaded
chat.data.friends.clear();
for( var i = 0; i < DATA.users.length; i += 1 ){
var user = DATA.users[i];
chat.data.friends.put( user.friend_id, user );
}
getFriend = function(id){ return chat.data.friends.get( id ); }
var friend = getFriend(66);
console.log(friend.name);
console.log(friend.username);
console.log(friend.thumb);

Categories