I have these object :
var obj1 = {
endDateInMs : 125000001
};
var obj2 = {
endDateInMs: 125000000
};
var obj3 = {
endDateInMs: 125000002
};
and an array containing these objects :
var array1 = [obj1, obj2, obj3];
I would like to sort array1 by date of object. I would like to have the more recent first and the oldiest at the end of the array.
I do the following but it does'nt work :
function compare(a,b) {
if (a.endDateInMs < b.endDateInMs) {
return -1;
}
else if (a.endDateInMs > b.endDateInMs) {
return 1;
}
}
var arrayOfHistoryForThisItem = wall_card_array[item];
var newArraySorted = arrayOfHistoryForThisItem.sort(compare);
var lastElement = newArraySorted[0];
Wouldn't it be just
array1.sort(function(a, b) {
return b.endDateInMs - a.endDateInMs;
});
FIDDLE
Using the open source project http://www.jinqJs.com, its easy.
See http://jsfiddle.net/tford/epdy9z2e/
//Use jsJinq.com open source library
var obj1 = {
endDateInMs : 125000001
};
var obj2 = {
endDateInMs: 125000000
};
var obj3 = {
endDateInMs: 125000002
};
var array1Ascending = jinqJs().from(obj1, obj2, obj3).orderBy('endDateInMs').select();
var array1Descending = jinqJs().from(obj1, obj2, obj3).orderBy([{field:'endDateInMs', sort:'desc'}]).select();
document.body.innerHTML = '<pre>' + JSON.stringify(array1Ascending, null, 4) + '</pre>';
document.body.innerHTML += '<pre>' + JSON.stringify(array1Descending, null, 4) + '</pre>';
Related
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);
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);
I created an object with Int values and some functions in js as below
var obj = function (int1,int2,int3){
this.int1=int1;
this.int2=int2;
this.int3=int3;
this.add= (function (){
return parseInt(int1)+parseInt(int2)+parseInt(int3)
}());
When I execute the code
var a= new obj(1,2,3);
console.log(a.add);
The Answer is
NaN
Type of all the int1,int2.int3,add is Number.
Whats the problem with My code & How to correct it
You need a instance of the function with new operator and you could skip parseInt, which works better with a given base.
var Obj = function (int1, int2, int3) {
this.int1 = int1;
this.int2 = int2;
this.int3 = int3;
this.add = function () {
return this.int1 + this.int2 + this.int3;
}
},
instance = new Obj(1, 2, 3);
console.log(instance.add());
Try this:
var obj = function(int1, int2, int3) {
this.int1 = int1;
this.int2 = int2;
this.int3 = int3;
this.add = function() {
return parseInt(int1) + parseInt(int2) + parseInt(int3)
}};
And, Call above as:
var a = new obj(1, 2, 3);
console.log(a.add());
run this code:
var obj = function (int1, int2, int3) {
this.int1 = int1;
this.int2 = int2;
this.int3 = int3;
this.add = (function () {
return parseInt(int1) + parseInt(int2) + parseInt(int3)
} ())
};
var a = new obj(1,2,3);
console.log(a.add); // 6
your code lost a }
Try this it's working fine :
var obj = function (int1,int2,int3){
this.int1=int1;
this.int2=int2;
this.int3=int3;
this.add= (function (){
return parseInt(int1)+parseInt(int2)+parseInt(int3)
}())
}
var a= new obj(1,2,3);
console.log(a.add); // 6
Working fiddle :
https://jsfiddle.net/90ku8qae/
Update :
You forgot to add the closing bracket for the function obj. I just added and everything is working fine now.
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);
I am using a YUI DataTable with a custom sortFunction that strips out HTML code, to sort based on the text content only, rather than the entire string with HTML tags. The problem that I am having is that I need to make use of this sort function on three different columns, and I can not seem to pass the "field" value into my sort function. I want to use "field" rather than naming the column - because I would like to use the same sort function for all three columns rather than repeat it three times as I have in the code below. When I pass in "field" the sort stalls or hangs in the browser and "field" seems to be "undefined". Any ideas?
YAHOO.util.Event.addListener(window, "load", function() {
var sortProject = function(a, b, desc) {
var col = "project";
// Deal with empty values
if(!YAHOO.lang.isValue(a)) {
return (!YAHOO.lang.isValue(b)) ? 0 : 1;
}
else if(!YAHOO.lang.isValue(b)) {
return -1;
}
var comp = YAHOO.util.Sort.compare;
var tagregex = /<[^>]*>/g;
var aString = a.getData(col).replace(tagregex, "");
var bString = b.getData(col).replace(tagregex, "");
var compString = comp(aString, bString, desc);
return compString;
};
var sortArchitect = function(a, b, desc) {
var col = "architect"
// Deal with empty values
if(!YAHOO.lang.isValue(a)) {
return (!YAHOO.lang.isValue(b)) ? 0 : 1;
}
else if(!YAHOO.lang.isValue(b)) {
return -1;
}
var comp = YAHOO.util.Sort.compare;
var tagregex = /<[^>]*>/g;
var aString = a.getData(col).replace(tagregex, "");
var bString = b.getData(col).replace(tagregex, "");
var compString = comp(aString, bString, desc);
return compString;
};
var sortStatus = function(a, b, desc) {
var col = "status"
// Deal with empty values
if(!YAHOO.lang.isValue(a)) {
return (!YAHOO.lang.isValue(b)) ? 0 : 1;
}
else if(!YAHOO.lang.isValue(b)) {
return -1;
}
var comp = YAHOO.util.Sort.compare;
var tagregex = /<[^>]*>/g;
var aString = a.getData(col).replace(tagregex, "");
var bString = b.getData(col).replace(tagregex, "");
var compString = comp(aString, bString, desc);
return compString;
};
var myColumnDefs = [
{key:"design",label:"<span class='dtTitleText'>Design</span>", width:105, formatter:YAHOO.widget.DataTable.formatDate, sortable:true},
{key:"status",label:"<span class='dtTitleText'>Status</span> <sup>1</sup>", sortable:true, width:62, sortOptions:{sortFunction:sortStatus}},
{key:"project",label:"<span class='dtTitleText'>Project Name</span>", sortable:true, width:105, sortOptions:{sortFunction:sortProject}},
{key:"address",label:"<span class='dtTitleTextNoSort'>Address</span>", width:80, sortable:false},
{key:"city",label:"<span class='dtTitleText'>City</span>", width:80, sortable:true},
{key:"state",label:"<span class='dtTitleText'>State</span>", width:45, sortable:true},
{key:"type",label:"<span class='dtTitleText'>Building <br />Type</span>", width:75, sortable:true},
{key:"feet",label:"<span class='dtTitleText'>Gross <br />Sq. Ft.</span>", width:55, formatter:YAHOO.widget.DataTable.formatNumber,sortable:true},
{key:"owner",label:"<span class='dtTitleText'>Building <br />Owner</span>", width:95, sortable:true},
{key:"architect",label:"<span class='dtTitleText'>Architect of <br />Record (AOR)</span>", width:115, sortable:true, sortOptions:{sortFunction:sortArchitect}}
];
var myDataSource = new YAHOO.util.DataSource(YAHOO.util.Dom.get("storableTable"));
myDataSource.responseType = YAHOO.util.DataSource.TYPE_HTMLTABLE;
myDataSource.responseSchema = {
fields: [{key:"design", parser:"number"},
{key:"status"},
{key:"project"},
{key:"address"},
{key:"city"},
{key:"state"},
{key:"type"},
{key:"feet", parser:"number"},
{key:"owner"},
{key:"architect"}
]
};
var myDataTable = new YAHOO.widget.DataTable("progEnhanceTable", myColumnDefs, myDataSource,
{sortedBy:{key:"design",dir:"desc"}, renderLoopSize: 50}
);
return {
oDS: myDataSource,
oDT: myDataTable
}; });
How about generating the sort functions in a function:
function makeSortFunction(col) {
return function(a, b, desc) {
// NOTE: the passed 'col' variable is available inside closure...
// Deal with empty values
if(!YAHOO.lang.isValue(a)) {
return (!YAHOO.lang.isValue(b)) ? 0 : 1;
}
else if(!YAHOO.lang.isValue(b)) {
return -1;
}
var comp = YAHOO.util.Sort.compare;
var tagregex = /<[^>]*>/g;
var aString = a.getData(col).replace(tagregex, "");
var bString = b.getData(col).replace(tagregex, "");
var compString = comp(aString, bString, desc);
return compString;
};
}
And use it as
{key:"status",label:"<span class='dtTitleText'>Status</span> <sup>1</sup>", sortable:true, width:62, sortOptions:{sortFunction:makeSortFunction('status')}},
{key:"project",label:"<span class='dtTitleText'>Project Name</span>", sortable:true, width:105, sortOptions:{sortFunction:makeSortFunction('project')}},
Rather than referring to the function, this is calling makeSortFunction(), which returns the actual sort function.