I have a nested object:
myObj = {
id:'AA',
child:{
id:'BB',
key1:'CC'
},
child2:{
id:'DD',
key1:'EE'
},
};
I also have a function where I am currently doing this:
doSomething = function(id,childid,key){
var str = id + childid + key;
console.log(str);
};
doSomething(myObj.id,myObj.child.id,myObj.child.key1);
I would like to simplify to this:
doSomething2 = function(incObj){
//myObj.child.key1;
var str = incObj.id + ' ' + incObj.child.id + ' ' + incObj.child.key;
//str = 'AA BB CC';
console.log(str);
}
doSomething2(myObj.child.key1);
Is there a clean/simple way of doing this?
The way you doing it:
myObj = {
id:'AA',
child:{
id:'BB',
key1:'CC'
},
child2:{
id:'DD',
key1:'EE'
},
};
doSomething2 = function(incObj){
//myObj.child.key1;
var str = incObj.id + ' ' + incObj.child.id + ' ' +incObj.child.key1;
//str = 'AA BB CC';
console.log(str);
}
doSomething2(myObj);
myObj = {
id:'AA',
child:{
id:'BB',
key1:'CC'
},
child2:{
id:'DD',
key1:'EE'
},
};
var config = {
"child" : "child2",
"key" :"key1"
}
doSomething2 = function(incObj, config){
//myObj.child.key1;
var str = incObj.id + ' ' + incObj[config.child].id + ' ' +incObj[config.child][config.key];
//str = 'AA BB CC';
console.log(str);
}
doSomething2(myObj,config);
You've already found the answer by yourself. You just have the pass the object and it's done.
Object:
myObj = {
id:'AA',
child:{
id:'BB',
key1:'CC'
},
child2:{
id:'DD',
key1:'EE'
},
};
function:
doSomething2 = function(incObj){
//myObj.child.key1;
var str = incObj.id + ' ' + incObj.child.id + ' ' + incObj.child.key1;
console.log(str);
}
doSomething2(myObj);
Related
if have javascript:
function calculateValues(callback)
{
window.external.getHistoryRange(0,1,"",function(res){
var hist = eval(res);
histCount = hist.historyCount;
hist = hist.historyContent;
if (histCount == 0)
{
return;
}
$("#history_table").show();
var $row = addAlertHistoryRow(hist[0]);
var rowHeight = $row.height();
pageItemsCount = Math.floor(contentHeight / rowHeight);
curPageNum = 0;
$row.remove();
if (callback) callback();
});
}
in function calculateValues(callback) callback parameter is:
function(){statItempos = 0; gethistoryandshow(pageNum,startItemsPos,callback);}
and c# code, that works with that script (ObjectForScripting):
public string getHistoryRange(string strVar0 = "", string strVar1 = "", string strVar2 = "", string strVar3 = "")
{
string res = "";
using (DeskAlertsDbContext db = new DeskAlertsDbContext())
{
var alerts = db.HistoryAlerts.OrderBy(a => a.ReciveTime)
.Include(b => b.alert.WINDOW)
.ToList();
foreach (var alert in alerts)
{
res += ("{\"id\":" + System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Alert_id) +
",\"date\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(
alert.ReciveTime.ToString(CultureInfo.InvariantCulture)) + "\",\"alert\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alerttext) + "\",\"title\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Title) + "\",\"acknow\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Acknown) + "\",\"create\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Create_date) + "\",\"class\":\"" +
"1" + "\",\"urgent\":\"" + System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Urgent) +
"\",\"unread\":\"" + Convert.ToInt32(alert.isclosed).ToString() + "\",\"position\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Position) + "\",\"ticker\":\"" +
alert.alert.Ticker + "\",\"to_date\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.To_date) + "\"},");
}
res = res.TrimEnd(','); //trim right ","
res = "({\"historyCount\":" + alerts.Count.ToString() + ",\"historyContent\":[" + res + "]});";
Browserwindow.Wb.InvokeScript("eval", new object[] { strVar3 });
Browserwindow.Wb.InvokeScript("CallbackFunction", new object[] { res });
return res;
}
}
On string: "Browserwindow.Wb.InvokeScript("eval", new object[] { strVar3 });"
I try to call anonymous function from javascript and have an error.
Question is: how to make this logic. How to perform the JS function of the parameters a different function. And then continue JS. If i tryed to give name to function, and invoke it, function works, but global context(if (callback) callback();) becomes unavailible
Your callback function name is not correct.
Replace
Browserwindow.Wb.InvokeScript("CallbackFunction", new object[] { res });
With
Browserwindow.Wb.InvokeScript("calculateValues", new object[] { res });
Hmmm... Just maked my variable dynamic (not string), and all worked
public string getHistoryRange(string strVar0 = "", string strVar1 = "", string strVar2 = "", dynamic strVar3 = null)
{
string res = "";
using (DeskAlertsDbContext db = new DeskAlertsDbContext())
{
var alerts = db.HistoryAlerts.OrderBy(a => a.ReciveTime)
.Include(b => b.alert.WINDOW)
.ToList();
foreach (var alert in alerts)
{
res += ("{\"id\":" + System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Alert_id) +
",\"date\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(
alert.ReciveTime.ToString(CultureInfo.InvariantCulture)) + "\",\"alert\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alerttext) + "\",\"title\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Title) + "\",\"acknow\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Acknown) + "\",\"create\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Create_date) + "\",\"class\":\"" +
"1" + "\",\"urgent\":\"" + System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Urgent) +
"\",\"unread\":\"" + Convert.ToInt32(alert.isclosed).ToString() + "\",\"position\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.Position) + "\",\"ticker\":\"" +
alert.alert.Ticker + "\",\"to_date\":\"" +
System.Web.HttpUtility.JavaScriptStringEncode(alert.alert.To_date) + "\"},");
}
res = res.TrimEnd(','); //trim right ","
res = "({\"historyCount\":" + alerts.Count.ToString() + ",\"historyContent\":[" + res + "]});";
dynamic variable = Browserwindow.Wb.InvokeScript("eval", new object[] { strVar3 });
variable(res);
return res;
}
}
I created this function to replace value in a string and call functions whose name is the value.
$(function() {
var str = "Homer drank {{countBeers}} beers";
function countBeers() {
console.log(this);
return 10 + 10;
}
function convert(str) {
console.log(this);
str = "'" + str.replace(/{{(.*?)}}/g, "' + $1.call(this) + '") + "'";
OR
str = "'" + str.replace(/{{(.*?)}}/g, "' + $1(this) + '") + "'";
return eval(str);
}
var output = convert.call(this, str);
$('body').append(output); //Homer drank 20 beers
});
This seems to work fine, but I would not use eval.
You can do it any other way?
Thank you
You could use an object with the function.
function convert(str) {
return str.replace(/{{(.*?)}}/g, function (_, f) {
return op[f] ? op[f]() : f;
});
}
var str = "Homer drank {{countBeers}} beers",
op = { countBeers: function () { return 10 + 10; } };
console.log(convert(str));
How do I concatenate these strings to get value from a variable. I want to avoid eval as so many of you are not keen on its use.
function getLesson() {
var lesson = "lesson" + localStorage.lessonNGS;
document.getElementById("lessonNumber").innerHTML = "Lesson " + (eval(lesson + "." + number));
document.getElementById("lessonTitle").innerHTML = (eval(lesson + "." + title));
document.getElementById("lessonScore").src = (eval(lesson + "." + score));
document.getElementById("mp3").src = (eval(lesson + "." + trackmp3));
document.getElementById("ogg").src = (eval(lesson + "." + trackogg));
document.getElementById("lessonTrack").load();
}
This works but I'm told it will cause me conflicts in some browsers.
Simply remove the eval
// Demo data
localStorage.setItem("lessonNGS",1);
var lesson1 = {
number: "1",
title: "Quarter Notes",
score: "scores/01_quarternotes.jpg",
trackmp3: "tracks/mp3/01_quarternotekeyexercises.mp3",
trackogg: "tracks/ogg/01_quarternotekeyexercises.ogg"
};
function getLesson() {
debugger;
var lesson = window["lesson" + localStorage.lessonNGS];
document.getElementById("lessonNumber").innerHTML = "Lesson " + lesson.number;
document.getElementById("lessonTitle").innerHTML = lesson.title;
document.getElementById("lessonScore").src = lesson.score;
document.getElementById("mp3").src = lesson.trackmp3;
document.getElementById("ogg").src = lesson.trackogg;
document.getElementById("lessonTrack").load();
}
Javascript String.prototype.concat():
str.concat(string2, string3[, ..., stringN])
Example:
var hello = 'Hello, ';
console.log(hello.concat('Kevin', ' have a nice day.'));
I'm trying to parse JSON in JavaScript. If my JSON data looks like below, I want to iterate through all the JSON elements that start with "custom" and not with any other string. How do I do this?
{
"fields": {
"custom12": {
value: "dsada"
},
"custom45": {
value: "adsadad"
},
"test12": {
value: "12323"
}
}
}
var newObject = {}, key;
for(key in data.fields){
if(key.search(/custom/) > -1){
newObject[key] = data.fields[key];
}
}
console.log(newObject);
The following iterates the properties of the fields object and checks whether the property's name contains custom:
var data = yourObjectLiteral, i, current;
for(i in data.fields) {
if(i.indexOf('custom') > -1) {
current = data.fields[i];
// ... your logic ...
}
}
With the json string you provided I'd do it as such:
<script src="json2.js"></script>
<script>
var raw = '{'
+ ' "fields": {'
+ ' "custom12": {'
+ ' "value": "dsada"'
+ ' },'
+ ' "custom45": {'
+ ' "value": "adsadad"'
+ ' },'
+ ' "test12": {'
+ ' "value": "12323"'
+ ' }'
+ ' }'
+ '}';
var data = JSON.parse(raw);
var fields = data.fields;
var message = '';
for (var key in fields) {
if (key.indexOf('custom') === 0) {
message += key + ': ' + fields[key].value + '\n';
}
}
alert(message);
</script>
But, if you can rewrite the incomming message a little it will look simpler.
<script src="json2.js"></script>
<script>
var raw = '{'
+ ' "custom12": "dsada",'
+ ' "custom45": "adsadad",'
+ ' "test12": "12323"'
+ '}';
var fields = JSON.parse(raw);
var message = '';
for (var key in fields) {
if (key.indexOf('custom') === 0) {
message += key + ': ' + fields[key] + '\n';
}
}
alert(message);
</script>
I have the following (example) array of objects:
var theArray = [
{theId:'1', num: 34},
{theId:'2', num: 23},
{theId:'5', num: 26}
];
and this function, which works fine to loop through them:
function printValues() {
var i = 0;
for(i; i<theArray.length; i++) {
var obj = theArray[i];
document.getElementById('result1').innerHTML += obj.theId + ' = ' + obj.num + '<br>';
}
}
However, if I want to abstract this function for use on similar arrays by using function variables to access objects within them, like this:
function printValuesVar(arr,elemId,arrId,arrNum) {
var i = 0;
for(i; i<arr.length; i++) {
var obj = arr[i];
document.getElementById(elemId).innerHTML += obj.arrId + ' = ' + obj.arrNum + '<br>';
}
}
'undefined' is the result when called as below (as I'd kind of expect since 'arrId' is not an object name):
printValuesVar(theArray,'result2','theId','num');
How can I use the values passed to the function's variables to access values of objects within the array by name?
rewritten following advice against antipatterns:
function printValuesVar(arr,elemId,arrId,arrNum) {
var i = 0;
var content = '';
for(i; i<arr.length; i+=1) {
var obj = arr[i];
content += obj[arrId] + ' = ' + obj[arrNum] + '<br>';
}
document.getElementById(elemId).innerHTML = content;
}
Try this:
function printValuesVar( arr, elemId, arrId, arrNum ) {
var content = '';
arr.forEach( function ( arrElem ) {
content += arrElem[ arrId ] + ' = ' + arrElem[ arrNum ] + '<br>';
});
document.getElementById( elemId ).innerHTML = content;
}
Or a bit more advanced:
function printValuesVar( arr, elemId, arrId, arrNum ) {
document.getElementById( elemId ).innerHTML = arr.map( function ( arrElem ) {
return arrElem[ arrId ] + ' = ' + arrElem[ arrNum ];
}).join( '<br>' );
}
ES5-shim for shitty browsers
Because you are loking for key "arrId", not the key stored in variable arrId
document.getElementById(elemId).innerHTML += obj[arrId] + ' = ' + obj[arrNum] + '<br>';