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

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

Related

convert JSON with html table tag using JavaScript

I am trying to convert output from SQL Query which comes as a table. I have converted the table as JSON. Now I am in a process of converting the JSON to HTML Table so that I can use it for reporting.
Script is given below,
var value = '{"root":{"row":[{"DatabaseID":"21","fileid":"1","databaseName":"AutomationPortal","FileLogicalName":"AutomationPortal","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomationPortal.mdf","FileSizeMB":"100.00","SpaceUsedMB":"10.25","MaxfileSizeMB":"-0.01","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"},{"DatabaseID":"21","fileid":"3","databaseName":"AutomationPortal","FileLogicalName":"AutomatioPortal_01","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomatioPortal_01.ndf","FileSizeMB":"100.00","SpaceUsedMB":"0.06","MaxfileSizeMB":"130.00","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"}]}}'
var data = JSON.parse(value);
var tablearray = [];
tablearray.push("<table><tr>")
var queryRow = data.root.row.length;
var headerProperty = Object.keys(data.root.row[0]);
for (i=0;i<headerProperty.length;i++){
tablearray.push("<th>"+headerProperty[i]+"</th>");
}
tablearray.push("</tr>");
//console.log(tablearray);
for (i=0;i<queryRow;i++){
tablearray.push("<tr>")
for (j=0;j<headerProperty.length;j++){
// console.log(headerProperty[j]);
// console.log(data.root.row[0].DatabaseID);
// console.log(data.root.row[i].headerProperty[j]);
tablearray.push("<td>"+data.root.row[i].headerProperty[j]+"</td>");
}
tablearray.push("</tr>");
}
tablearray.push("</table>");
tablearray.join('');
When I run the above script it gives me the following error, I am unable to fix the issue.
tablearray.push(""+data.root.row[i].headerProperty[j]+"");
^
TypeError: Cannot read property '0' of undefined
at Object. (C:\Users\convertjsontohtml.js:21:55)
at Module._compile (internal/modules/cjs/loader.js:678:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:689:10)
at Module.load (internal/modules/cjs/loader.js:589:32)
at tryModuleLoad (internal/modules/cjs/loader.js:528:12)
at Function.Module._load (internal/modules/cjs/loader.js:520:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:719:10)
at startup (internal/bootstrap/node.js:228:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:575:3)
The Output I am expecting is like ""
You can build the table by looping thought each value like this:
const input = '{"root":{"row":[{"DatabaseID":"21","fileid":"1","databaseName":"AutomationPortal","FileLogicalName":"AutomationPortal","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomationPortal.mdf","FileSizeMB":"100.00","SpaceUsedMB":"10.25","MaxfileSizeMB":"-0.01","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"},{"DatabaseID":"21","fileid":"3","databaseName":"AutomationPortal","FileLogicalName":"AutomatioPortal_01","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomatioPortal_01.ndf","FileSizeMB":"100.00","SpaceUsedMB":"0.06","MaxfileSizeMB":"130.00","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"}]}}';
// Parse given JSON
const parsed = JSON.parse(input);
// Get keys (=cells) of each items
const keys = Object.keys(parsed.root.row[0]);
// Build the table header
const header = `<thead><tr>` + keys
.map(key => `<th>${key}</th>`)
.join('') + `</thead></tr>`;
// Build the table body
const body = `<tbody>` + parsed.root.row
.map(row => `<tr>${Object.values(row)
.map(cell => `<td>${cell}</td>`)
.join('')}</tr>`
).join('');
// Build the final table
const table = `
<table>
${header}
${body}
</table>
`;
// Append the result into #root element
document.getElementById('root').innerHTML = table;
<div id="root"></div>
This is my generic code to convert any json (containing Object add/or List). Building a table like this can be used to visualize our json and at times even use it in production code for debugging support.
const getType = obj => Object.prototype.toString.call(obj).slice(8, -1);
const isArray = obj => getType(obj) === 'Array';
const isMap = obj => getType(obj) === 'Object';
var buildList = function(data) {
const keys = new Set();
var str = "<table border==\"0\"><tr>";
for (var i = 0; i < data.length; i++) {
for (key in data[i]) {
keys.add(key);
}
}
for (key of keys) {
str = str.concat('<td>' + key + '</td>');
}
str = str.concat("</tr>");
for (var i = 0; i < data.length; i++) {
str = str.concat('<tr>');
for (key of keys) {
str = str.concat('<td>');
if (data[i][key]) {
if (isMap(data[i][key])) {
str = str.concat(buildMap(data[i][key]));
} else if (isArray(data[i][key])) {
str = str.concat(buildList(data[i][key]));
} else {
str = str.concat(data[i][key]);
}
}
str = str.concat('</td>');
}
str = str.concat('</tr>');
}
str = str.concat("</table>");
return str;
}
var buildMap = function(data) {
var str = "<table border==\"0\">";
for (const key in data) {
str = str.concat('<tr><td>' + key + '</td><td>');
if (isArray(data[key])) {
str = str.concat(buildList(data[key]));
} else if (isMap(data[key])) {
str = str.concat(buildMap(data[key]));
} else {
str = str.concat(data[key]);
}
str = str.concat('</td></tr>');
}
str = str.concat("</table>");
return str;
}
var value = '{"root":{"row":[{"DatabaseID":"21","fileid":"1","databaseName":"AutomationPortal","FileLogicalName":"AutomationPortal","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomationPortal.mdf","FileSizeMB":"100.00","SpaceUsedMB":"10.25","MaxfileSizeMB":"-0.01","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"},{"DatabaseID":"21","fileid":"3","databaseName":"AutomationPortal","FileLogicalName":"AutomatioPortal_01","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomatioPortal_01.ndf","FileSizeMB":"100.00","SpaceUsedMB":"0.06","MaxfileSizeMB":"130.00","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"}]}}';
var data = JSON.parse(value);
var outHtml = "No Data found";
if (isArray(data)) {
outHtml = buildList(data);
} else if (isMap(data)) {
outHtml = buildMap(data);
}
document.getElementById("main").innerHTML = outHtml;</script>
<div id="main"></div>
The problem is that your rows don't have a property called "headerProperty". I think you are wanting to use the value inside headerProperty[j] as a dynamic property name?
For that you have to use "bracket notation" to write the property accessor - this allows you to use any string value as the property name at runtime:
data.root.row[i][propertyHeader[j]]
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors for a bit more info.
Demo - I hope this now outputs what you expected:
var value = '{"root":{"row":[{"DatabaseID":"21","fileid":"1","databaseName":"AutomationPortal","FileLogicalName":"AutomationPortal","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomationPortal.mdf","FileSizeMB":"100.00","SpaceUsedMB":"10.25","MaxfileSizeMB":"-0.01","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"},{"DatabaseID":"21","fileid":"3","databaseName":"AutomationPortal","FileLogicalName":"AutomatioPortal_01","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomatioPortal_01.ndf","FileSizeMB":"100.00","SpaceUsedMB":"0.06","MaxfileSizeMB":"130.00","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"}]}}'
var data = JSON.parse(value);
var tablearray = [];
tablearray.push("<table><tr>")
var queryRow = data.root.row.length;
var headerProperty = Object.keys(data.root.row[0]);
for (i = 0; i < headerProperty.length; i++) {
tablearray.push("<th>" + headerProperty[i] + "</th>");
}
tablearray.push("</tr>");
//console.log(tablearray);
for (i = 0; i < queryRow; i++) {
tablearray.push("<tr>")
for (j = 0; j < headerProperty.length; j++) {
// console.log(headerProperty[j]);
// console.log(data.root.row[0].DatabaseID);
// console.log(data.root.row[i].headerProperty[j]);
tablearray.push("<td>" + data.root.row[i][headerProperty[j]] + "</td>");
}
tablearray.push("</tr>");
}
tablearray.push("</table>");
document.write(tablearray.join(''));
There is no headerProperty available inside the data.root.row[0]
Instead of working with strings you might want to create elements using document.createElement
const value = '{"root":{"row":[{"DatabaseID":"21","fileid":"1","databaseName":"AutomationPortal","FileLogicalName":"AutomationPortal","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomationPortal.mdf","FileSizeMB":"100.00","SpaceUsedMB":"10.25","MaxfileSizeMB":"-0.01","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"},{"DatabaseID":"21","fileid":"3","databaseName":"AutomationPortal","FileLogicalName":"AutomatioPortal_01","FileFullPath":"D:\\\\MSSQL13.MSSQLSERVER\\\\MSSQL\\\\DATA\\\\AutomatioPortal_01.ndf","FileSizeMB":"100.00","SpaceUsedMB":"0.06","MaxfileSizeMB":"130.00","SPaceOnVolumeMB":"95110.38","AutogrowSetting":"8192"}]}}'
const data = JSON.parse(value);
console.log(data);
const $table = document.createElement('table');
const $head = document.createElement('thead');
const $body = document.createElement('tbody');
for (let i = 0; i < data.root.row.length; i++) {
const $tr = document.createElement('tr');
Object.keys(data.root.row[0]).forEach((colName) => {
if (i === 0) {
const $th = document.createElement('th');
$th.innerText = colName;
$head.appendChild($th);
}
const $td = document.createElement('td');
$td.innerText = data.root.row[0][colName];
$tr.appendChild($td);
});
$body.appendChild($tr);
}
$table.appendChild($head);
$table.appendChild($body);
document.getElementById('table').appendChild($table);
<div id="table"></div>

Javascript looping through variables

So right now this is my current code and I'm trying to figure out a way to loop through the variables I've already declared (Assuming variables 1-9 already have values). I just wanted to know whether this was possible at all?
var title;
var brief;
var hover;
var whatTitle;
var whatDesc;
var whyTitle;
var whyDesc;
var funTitle;
var funDesc;
var titles = [];
var briefs = [];
var hovers = [];
var whatTitles = [];
var whatDescs = [];
var whyTitles = [];
var whyDescs = [];
var funTitles = [];
var funDescs = [];
var obj = {'titles' : title};
if(localStorage.getItem('titles') != null) {
var tmp = JSON.parse(localStorage.getItem('titles'));
for(var i = 0;i<tmp.length;i++) {
titles.push(tmp[i]);
}
}
titles.push(obj);
localStorage.setItem("titles", JSON.stringify(titles));
Output I want if we printed out the looped code:
var obj = {'titles' : title};
if(localStorage.getItem('titles') != null) {
var tmp = JSON.parse(localStorage.getItem('titles'));
for(var i = 0;i<tmp.length;i++) {
titles.push(tmp[i]);
}
}
titles.push(obj);
localStorage.setItem("titles", JSON.stringify(titles));
var obj = {'briefs' : brief};
if(localStorage.getItem('briefs') != null) {
var tmp1 = JSON.parse(localStorage.getItem('briefs'));
for(var i = 0;i<tmp.length;i++) {
briefs.push(tmp[i]);
}
}
briefs.push(obj);
localStorage.setItem("briefs", JSON.stringify(briefs));
var obj = {'hovers' : hover};
if(localStorage.getItem('hovers') != null) {
var tmp2 = JSON.parse(localStorage.getItem('hovers'));
for(var i = 0;i<tmp.length;i++) {
hovers.push(tmp[i]);
}
}
hovers.push(obj);
localStorage.setItem("hovers", JSON.stringify(hovers));
...etc
If the code is running in a browser, then you can do something like:
for(key in window) { console.log(window[key]) } // print all variables
The variables are associated to the global namespace. That is to say the upmost "this" reference or the window object.
You're almost there with the code you have. If you look at your "desired output" examples, you'll see that the only thing that really differs between each element of your "unrolled loop" is the key for local storage ('titles', 'briefs', 'hovers').
With that in mind, you could use an Object to map the keys to the variables you have at the top level. So this:
var titles = [];
var briefs = [];
var hovers = [];
var whatTitles = [];
var whatDescs = [];
...
Becomes (UPDATE: with the initializer values preserved):
var key_to_collection = {
'titles': [title],
'briefs': [brief],
'hovers': [hovers],
'whatTitles': [whatTitles],
'whatDescs': [whatDescs],
}
Then, you loop over the values of this object:
Object.keys(key_to_collection).forEach(function(key) {
var obj = {};
collection = key_to_collection[key];
obj[key] = collection;
if(localStorage.getItem(key) != null) {
var tmp = JSON.parse(localStorage.getItem(key));
for(var i = 0;i<tmp.length;i++) {
collection.push(tmp[i]);
}
}
collection.push(obj);
localStorage.setItem(key, JSON.stringify(collection));
});
If your variable name is title for example, then you can access it using window['title']. This means that if you define an array of your global variable names:
const varNames = ['title', 'brief', 'hover', ...]
Then you can do a loop like the following
for(const name of varNames) {
const value = window[name]
// do whatever you want using the variable name and value
}
I hope this solves your issue :)

Get variables from URL and convert to array

I need to retrieve variables from an URL.
I use this found function:
function getParams(str) {
var match = str.replace(/%5B/g, '[').replace(/%5D/g, ']').match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
obj[name] = obj[name] || [];
obj[name].push(value);
}
return obj;
}
var urlexample = "http://www.test.it/payments/?idCliente=9&idPagamenti%5B%5D=27&idPagamenti%5B%5D=26"
var me = getParams(stringa);
The output is:
{"idPagamenti":["26","27"],"idCliente":["9"]}
But idCliente is always NOT an array, so i'd like to retrieve:
{"idPagamenti":["26","27"],"idCliente": 9 }
This is the fiddle example
function getParams(str) {
var match = str.replace(/%5B/g, '[').replace(/%5D/g, ']').match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
obj[name] = obj[name] || [];
obj[name].push(value);
}
return obj;
}
var stringa = "http://www.test.it/payments/?idCliente=9&idPagamenti%5B%5D=27&idPagamenti%5B%5D=26"
var me = getParams(stringa);
$(document).ready(function(){
alert("testing");
console.log(me);
$(".a").html(JSON.stringify(me));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a">
</div>
Someone can help me to modify code?
I think your facing a real paradigm problem. Why idCliente wouldn't be an array but idPagamenti would be. You should have all array or none but not both. getParams() function can make this choice for you and you should probably change the way you are working with this.
Anyway, here is a getParams() function that replace any single-valued array to a value. Note that if you have only one idPagamenti in your URI, you will also have a single value for idPagamenti instead of an array.
function getParams(str) {
var match = str.replace(/%5B/g, '[').replace(/%5D/g, ']').match(/[^=&?]+\s*=\s*[^&#]*/g);
var obj = {};
for ( var i = match.length; i--; ) {
var spl = match[i].split("=");
var name = spl[0].replace("[]", "");
var value = spl[1];
obj[name] = obj[name] || [];
obj[name].push(value);
}
Object.keys(obj).forEach(key => {
if (obj[key].length === 1) {
obj[key] = obj[key][0];
}
})
return obj;
}
var urlexample = "http://www.test.it/payments/?idCliente=9&idPagamenti%5B%5D=27&idPagamenti%5B%5D=26"
var me = getParams(stringa);
If you know that you will always get ids as parameters, you can also add a parseInt() for each parameter by replacing var value = spl[1]; with var value = parseInt(spl[1], 10);

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