How can I iterate through this object in js? - javascript

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);

Related

How to replace the $ symbol from json object key in nodejs

I am trying to remove the $ symbol from the key in json object(parsed). Normal JS file I used Remove special character in json key name in nodejs this answer mentioned and it is working fine. But I tried in nodejs due to async it is not working properly. The last formed object did not contain the entire modified value. So I tried the original function which is posted in the question but I am getting callback function not found error. I am using node 10.19 version. Is there any other way I can remove the $ symbol from my json object. Please give me a working solution. Actualy I am getting the input from yml file which gets converted to json string in jenkins. And again In my code I have parsed it. If there any library to directly convert yml file to json in jenkins that will also help.
var obj = {
'blue':{
'test:"value',
'$test1':'value1',
'tiger':'cheetah_growl',
'$jan':'cool'
}
}
Normal js file
var obj_new = { '$name': 'test1', '$auth_users': 'bajali_s' };
console.log("obj.blue",obj.blue.tiger);
var str = obj.blue.tiger;
var res = str.replace("_", " ");
console.log("res",res);
obj.blue.tiger = res;
console.log("obj.blue",obj.blue.$test1);
//const obj1 = {"example1.":"sometext.","example2.":"anothertext."};
const obj2 = {};
console.log(Object.getOwnPropertyNames(obj));
const obj1 = obj_new;
console.log("__",obj1);
/* for (const key of Object.getOwnPropertyNames(obj1)) {
obj2[key.replace(/[|&;$%#."<>()+,]/g, "")] = obj1[key];
} */
for (const key of Object.getOwnPropertyNames(obj1)) {
obj2[key.replace(/[|&;$%#."<>()+,]/g, "")] = obj1[key];
}
console.log("==",obj2);
var newjson = JSON.stringify(obj2);
console.log(newjson);
Here is what I did to remove the extra symbol in the key and value. I went through many sites and came up with this procedure hope it helps someone. I have also made it little dynamic.
var special_char_keys = ["creationType", "vm_location", "nic_location", "vnetlocation", "rg_location"];
var elements_to_delete = ["blueprint_info", "riglet_info", "quick_links"];
for (var a = elements_to_delete.length; a >= 0; a--) {
delete cloudProperties[elements_to_delete[a]];
}
var Mainkeys = Object.keys(cloudProperties);
console.log("Mainkeys", Mainkeys);
var total_keys_cloudproperties = Mainkeys.length;
for (var j = total_keys_cloudproperties; j > 0; j--) { // main json loop starts
for (const key of Object.getOwnPropertyNames(cloudProperties)) { // getting the main json keys
var obj1 = cloudProperties[key];
var obj2 = {};
var obj3 = {};
var obj4 = {};
var obj5 = {};
var formattedarray = [];
var keys = Object.keys(cloudProperties[key]);
//console.log("inner keys", keys);
var tasksToGo = keys.length;
//console.log("key length",tasksToGo);
for (var i = tasksToGo; i > 0; i--) {
for (const key1 of Object.getOwnPropertyNames(obj1)) {
// var item = obj1.get(key1); // this will get the value in the json based on key
if (Array.isArray(obj1[key1])) { // checking whether the key has value as [{},{}]
// console.log("for jsonarray case");
var temparray = obj1[key1]; // assigning the array to temparray
for (var k = 0; k < temparray.length; k++) { // for loop for getting each object value
var obj3 = temparray[k]; // assigning the inner object to a variable
var Arraykeys = Object.keys(obj3);
// console.log("array inner keys", Arraykeys);
var tasksToGo1 = Arraykeys.length;
for (var t = tasksToGo1; t > 0; t--) {
for (const key2 of Object.getOwnPropertyNames(obj3)) {
if (special_char_keys.includes(key2)) {
var tempvalue = obj3[key2];
var newvalue = tempvalue.replace("_", " ");
// console.log("newvalue", newvalue);
obj4[key2.replace(/[|&;$%#."<>()+,]/g, "")] = newvalue;
} else {
obj4[key2.replace(/[|&;$%#."<>()+,]/g, "")] = obj3[key2];
}
// obj4[key2.replace(/[|&;$%#."<>()+,]/g, "")] = obj3[key2];
}
if (Arraykeys == tasksToGo1) {
break;
}
temparray[k] = obj4;
// console.log("temparray[k] ======================", temparray[k]);
}
}
obj5[key1] = temparray;
cloudProperties[key] = obj5;
// console.log("vm case", cloudProperties[key]);
} else {
// console.log("for normal case");
if (special_char_keys.includes(key1)) {
var tempvalue = obj1[key1];
// console.log(obj1[key1]);
var newvalue = tempvalue.replace("_", " ");
// console.log("newvalue", newvalue);
obj2[key1.replace(/[|&;$%#."<>()+,]/g, "")] = newvalue;
cloudProperties[key] = obj2;
} else {
obj2[key1.replace(/[|&;$%#."<>()+,]/g, "")] = obj1[key1];
cloudProperties[key] = obj2;
}
//obj2[key1.replace(/[|&;$%#."<>()+,]/g, "")] = obj1[key1];
// cloudProperties[key] = obj2;
}
}
}
//console.log("obj2",obj2);
//console.log("+++++++++++++++++",cloudProperties[key]);
}
if (j == total_keys_cloudproperties) {
//console.log("inside break");
break;
}
}
console.log("After removing", cloudProperties);

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);
...
}

JavaScript data structure : key/value with key access from the value

I need a data structure to store several JavaScript objects, and to be able to access them with a string id (get/set/delete operations).
Here is an example of the items I need to store :
var Player = function(name) {
this.name = name;
this.x = 0;
this.y = 0;
this.toString = function() {
return 'player : ' + this.name + ' at ' + this.x + ', ' + this.y;
};
}
I would like to store players in a data structure and to be able to get/set/delete them by their name, like players.get('Bob') to get the player with Bob as name.
At first, I thought I could use a map with the name as key (I'm using Dict from collectionsjs). But then I can't access the name from the methods of the item (toString in my example).
I could use a regular Array, keep the name attribute and implement my own get/set/delete methods, however I would rather use a reliable data structure but I can't find it.
Thanks in advance :]
A Javascript object would work.
var players = [];
players[0] = {"name":"Bob", "age":1};
players[1] = {"name":"John", "age":4};
for (var i in players) {
if (players[i].name == "Bob") {
alert("Bob is " + players[i].age);
}
}
EDIT:
var players = [];
players[0] = {"name":"Bob", "age":1};
players[1] = {"name":"John", "age":4};
players.forEach(function(player){
if (player.name == "Bob") {
alert("Bob is " + player.age);
}
});
var Players = function(){
this.players = [];
this.add = function(player){
this.players.push(player);
}
this.delete = function(name){
for(var i=0;i<this.players.length;i++)
if(this.players[i].name==name)
{
var f = this.players.slice(i+1,this.players.length+1);
this.players = this.players.slice(0,i).concat(f);
return;
}
}
this.set = function(name,player){
for(var i=0;i<this.players.length;i++)
if(this.players[i].name==name)
{
this.players[i] = player;
return;
}
}
this.show = function(){
for(var i=0;i<this.players.length;i++)
console.log(this.players[i].toString());
}
}
var p = new Players();
p.add(new Player('Lorem'));
p.add(new Player('Ipsum'));
p.show();
p.delete('Ipsum');
p.show();
What's unreliable about an array? Use the built in methods IMO. A simple example:
var players = [];
var Player = function(name) {
this.name = name;
this.x = 0;
this.y = 0;
this.toString = function() {
return 'player : ' + this.name + ' at ' + this.x + ', ' + this.y;
};
}
function getPlayerByName(name){
return players.filter(function(p){
return p.name.toLowerCase() === name.toLowerCase();
})[0];
}
// etc...
players.push(new Player('foo'));
var fetched = getPlayerByName('foo');
console.log(fetched);
http://jsfiddle.net/cy39sqge/

sort an object based on value in js

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);
})

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