How to append function with object as a parameter in javascript string? - javascript

<script>
//some code here
var content = '<div onclick="populatedata(\'' + obj.Records[t] + '\')" >';
function populatedata(obj) {
console.log(typeof obj);
}
</script>
Now output of the above code is string, but I want object content in function populatedata.

As #nnnnnn Suggested I had passed index of record in function and received it in populatedata.
<script>
//some code here
var content = "<div onclick="populatedata("+t+")>";
function populatedata(index) {
console.log(obj.Records[index]); //this is just for illustration
//further processing here
}
</script>

You didn't clarify what type obj.Records[t] is, but I guess it is an object. So you have problem because result of concatenation with a String is always a new string, with toString() applied to non-string types (obj.Records[t] in your case).
What you need to do is to stringify your object manually so that you control string presentation yourself:
var content = '<div onclick="populatedata(' + JSON.stringify(obj.Records[t]) + ')">';
Then result of such concatenation would be something like (if obj.Records[t] = {name: 123}):
<div onclick="populatedata({"name":123})">
which will allow populatedata invocation with proper parameter.

If you want to be able to further process the argument of populatedata, you'll first want to stringify it, then change your function from logging the typeof to just the object.
var content = "<div onclick='populatedata(" + JSON.stringify(obj.Records[t]) + ")'>test</div>";
function populatedata(obj) {
// do things with obj here
console.log(obj);
}
However, as Oriol mentioned in a comment on your question, you probably don't want to take that approach. It's better to:
Manage handlers through the dom API
Pass data objects in programmatically as opposed to embedding them into the dom

Related

How do I set multiple values of a JSON object?

So I've been working on this project but I'm stuck because I can't figure out how I should go about setting the other values of this new JSON object. So basically on the front end I have this:
HTML page view. The 'cat4' ID is the new object I tried to create, and illustrates the error I'm trying to fix. The problem is that I'm having trouble setting the LIMIT value of newly created objects (or multiple values at all). Here is the code where the object is created:
function sendCat()
{
window.clearTimeout(timeoutID);
var newCat = document.getElementById("newCat").value
var lim = document.getElementById("limit").value
var data;
data = "cat=" + newCat + ", limit=" + lim;
var jData = JSON.stringify(data);
makeRec("POST", "/cats", 201, poller, data);
document.getElementById("newCat").value = "Name";
document.getElementById("limit").value = "0";
}
In particular I've been playing around with the line data = "cat=" + newCat + ", limit=" + lim; but no combination of things I try has worked so far. Is there a way I can modify this line so that when the data is sent it will work? I find it odd that the line of code works but only for setting one part of the object.
The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
MDN
I think this is what you want:
const newCat = 'Meow';
const newLimit = 5;
const data = {
cat: newCat,
limit: newLimit
}
console.log(JSON.stringify(data));
What you're referring to as a 'JSON object' is actually just a javascript object, you can make one using object literal syntax. An object literal with multiple properties looks like this:
var data = {
cat: newCat,
limit: lim
};
makeRec("POST", "/cats", 201, poller, JSON.stringify(data));
assuming the fifth parameter to makeRec is supposed to be the POST request body as stringified JSON, as your code seems to imply

How to fully dump / print variable to console in the Dart language?

Hey there I am searching for a function which is printing a dynamic variable as completely as possible to the console in Dart language.
In PHP for instance I would use var_dump() in order to get all information about a variable.
In JavaScript I would do one of the following:
1) Convert Object to JSON and print console.log(JSON.stringify(obj))
2) Or a custom function like this:
function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;
//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += " ";
if(typeof(arr) == 'object') { //Array/Hashes/Objects
for(var item in arr) {
var value = arr[item];
if(typeof(value) == 'object') { //If it is an array,
dumped_text += level_padding + "'" + item + "' ...\n";
dumped_text += dump(value,level+1);
} else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}
However in Dart if I do print(variable) I get something like Instance of 'FooBarObject'. I cannot just convert an object to JSON like in JavaScript as this is not possible for all objects.
So my question in detail:
Is where a function or custom function in dart which can print a variable with unknown type (object, array, etc.) including all (public) properties as well as nested objects and variables to my console? Or which function is closest to this desire?
dart:developer library includes inspect function that allows debuggers to open an inspector on the object.
To use it add:
import 'dart:developer';
And then you can see your inspected variable/object in console with:
inspect(myVar);
There is no built in function that generates such an output.
print(variable) prints variable.toString() and Instance of 'FooBarObject' is the default implementation. You can override it in custom classes and print something different.
You can use reflection (https://www.dartlang.org/articles/libraries/reflection-with-mirrors) to build a function yourself that investigates all kinds of properties of an instance and prints it the way you want.
There is almost no limitation of what you can do and for debugging purposes it's definitely a fine option.
For production web application it should be avoided because it limits tree-shaking seriously and will cause the build output size to increase notable.
Flutter (mobile) doesn't support reflection at all.
You can also use one of the JSON serialization packages, that make it easy to add serialization to custom classes and then print the serialized value.
For example
https://pub.dartlang.org/packages/dson
I think there are others, but I don't know about (dis)advantages, because I usually roll my own using https://pub.dartlang.org/packages/source_gen
If it's a map then you can convert to JSON. First import convert package from flutter.
import 'dart:convert';
then convert to JSON and print
print(json.encode(yourMapVariable));
Update
Above answer is for map. For class / object add to toString() method.
Eg: say we have a user class
class User {
String name;
String address;
toString() {
return "name: " + name + ", address: " + address;
}
}
You can auto generate this toString() method using your IDE.
Simple little trick does the job
void printObject(Object object) {
// Encode your object and then decode your object to Map variable
Map jsonMapped = json.decode(json.encode(object));
// Using JsonEncoder for spacing
JsonEncoder encoder = new JsonEncoder.withIndent(' ');
// encode it to string
String prettyPrint = encoder.convert(jsonMapped);
// print or debugPrint your object
debugPrint(prettyPrint);
}
// To use simply pass your object to it
printObject(yourObject);
Instance of 'FooBarObject' This happens when you try to directly do print(object);
Even if you use convert package from flutter, it would throw Uncaught Error: Converting object to an encodable object failed:
To resolve this issue, first, make sure your model class or data class contains fromJson and toJson methods.
If you do so, your model class would look like this.
class User {
String name;
String gender;
int age;
User({this.name, this.gender, this.age});
User.fromJson(Map<String, dynamic> json) {
name = json['name'];
gender = json['gender'];
age = json['age'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['name'] = this.name;
data['gender'] = this.gender;
data['age'] = this.age;
return data;
}
}
And to print this as json import convert package
import 'dart:convert';
And call json.encode
//after initializing the user object
print('value is--> ' + json.encode(user);
Which will print the data as
value is--> {"name": "Vignesh","gender": "Male","age": 25}
use await keyword with an object in async function
void _registerUser() async { print(await form.result); }
If you want to know more about an instance of any class in an android studio click on a class name before variable then press ctrl+b it will take you to the class file where this object belongs from there you can see user attributes and methods of this class.
Try this one..
void printWrapped(String text) {
final pattern = new RegExp('.{1,800}'); // 800 is the size of each chunk
pattern.allMatches(text).forEach((match) => print(match.group(0)));
}

Assigning a JSON object to data field

I am dynamically creating a row using javascript, here is the code below:
var row2 = "<tr><td><a href='#editModal' class='modal_trigger' data-info="+name+" data-toggle='modal'>Edit</a></td></tr>";
The var here is a JSON object. This is later passed onto the modal when a user clicks it and values can be retrieved. However, simply declaring var like I have done above sets data-info=[Object object].
The content of the JSON variable is:
Object
name: "Test 8"
created_at: "2015-06-10 16:54:45"
id: 128
updated_at: "2015-06-10 16:54:45"
__proto__: Object
Is there a way around it?
Some advice here:
Don't use var as a variable name, even in examples (real code won't even compile)
Please, make sure you understand what JSON is, because Javascript object != JSON. Clearly var is a JS object in this case.
Said that, you can transform any JS object that does not contain functions into a JSON string with JSON.stringify(variable):
UPDATE: This is what I mean:
var row2 = '<tr><td><a href="#editModal" class="modal_trigger" data-info="'+
name+'" data-toggle="modal">Edit</a></td></tr>';
(Note the changes using quotation marks)
If you get [object Object] then it is not a JSON, is an Object.
JSON is a string containing an object serialized, and it is used as a lightweight data-interchange format.
Try serializing the object to JSON
"...data-info=" + JSON.stringify(myVar||null) + " data..."
Here I added coercion to null to prevent an error when the variable contains no data.
please Use JSON.stringify(yourVar).
var row2 = "<tr><td><a href='#editModal' class='modal_trigger' data-info="+JSON.stringify(yourVar)+" data-toggle='modal'>Edit</a></td></tr>";
Store your name variables in some mapping or array, store the id or the index in your row, and use this to fetch it back later :
// using a mapping :
var infoMapping = {};
function createRow (name) {
// this will work if 'id' is a key which identifies the object
infoMapping[name.id] = name;
var row2 = "<tr><td><a href='#editModal' ... data-infoid="+name.id+" ... ";
// etc ...
}
function editModal (nRow) {
var infoid = $(nRow).attr('data-infoid');
var name = infoMapping[infoid];
// use name ...
}
var x = {a:10, b:20};
var html = "<div data-info='" + JSON.stringify(x) + "'></div>";
Result is
"<div data-info='{"a":10,"b":20}'></div>"

Store values in javascript object with same keys

I have the following code to extract values from a JSON response. What I am trying to do is store the data in a similar way to how you would with an associative array in php. Apologies for the code being inefficient. The array comments written down are how I would like it to look in the object.
$.each(responseData, function(k1,v1){
if(k1 == "0"){
$.each(v1, function(k2,v2){
$.each(v2, function(k3, v3){
if(k3 == "val"){
//store in object here
//Array1 = array("time"=>k2, "iVal"=>v3)
console.log(k3 + v3 + k2);
}else{
//Array2 = array("time"=>k2, "aVal"=>v3)
console.log(k3 + v3 + k2);
}
});
});
}
});
So all the information is there but I am not sure how to store each instance for the values in an object. I did try store it like this:
//obj created outside
obj1.date = k2;
obj2.iVal = v3;
But doing this clearly overwrote every time, and only kept the last instance so I am wondering how can I do it so that all values will be stored?
Edit: Added input and output desired.
Input
{"0":{"18.00":{"iVal":85.27,"aVal":0.24},"19.00":{"iVal":85.27,"aVal":0.36},"20.00":{"iVal":0,"aVal":0}}, "success":true}
Desired output
array1 = {"time":"18.00", "iVal":85.27},{"time":"19.00", "iVal":85.27},{"time":"20.00", "iVal":0}
array2 = {"time":"18.00", "aVal":0.24},{"time":"19.00", "aVal":0.36},{"time":"20.00", "aVal":0}
try this :
var g1=[];
var g2=[];
for ( a in o[0])
{
g1.push({time:a , iVal:o[0][a]['iVal']})
g2.push({time:a , aVal:o[0][a]['aVal']})
}
http://jsbin.com/qividoti/3/edit
a json response can be converted back to a js object literal by calling JSON.parse(jsonString) inside the success callback of your ajax call.
from then on there is no need for iterating over that object since you navigate it like any other js object which is can be done in two ways either
the js way -> dot notation
var obj = JSON.parse(jsonStirng);
var value = obj.value;
or like a php array
var value = obj["value"];

Unexpected empty key-value in JSON string

I'm trying to parse a json string embedded in my html file.
Here is the reduced code.
<html>
<head>
<script src="./jquery-1.4.4.min.js" type="text/javascript"></script>
<script>
function parse_json(){
var jtext = $("#mtxt").text();
var jdata = jQuery.parseJSON(jtext);
JSON.parse(JSON.stringify(jdata), function (key, value){
alert("key=" + key + " value=" + value);
if(key== ""){
alert("value in string" + JSON.stringify(value));
}
});
}
$(document).ready(function() {
$("#run").click( function () {
parse_json();
});
});
</script>
</head>
<body>
<a id="run" href="#">run</a>
<div id="mtxt">
{"caller": "539293493"}
</div>
</body>
</html>
When I parse it, apart from the expected "caller" value, I get an extra empty "key" and "value".
The first alert gives me
key= value=[object Object]
The second alert gives me
value in string{}
What is happening? Why this extra entry?
Ok, you're passing the second param to JSON.parse() which is the reviver callback. Per the JSON docs, This callback is executed "...for every key and value at every level of the final result. Each value will be replaced by the result of the reviver function. This can be used to reform generic objects into instances of pseudoclasses, or to transform date strings into Date objects."
Since your reviver callback doesn't return anything, your object is getting improperly manipulated and distorted. I don't believe you have any use for the reviver in your use here. I have never seen it in use anywhere, and I use JSON.parse a LOT.
Your code should look like this:
function parse_json()
{
var jtext = $("#mtxt").text(),
jdata = JSON.parse( $.trim( jtext ) ),
key,
value;
for( key in jdata )
{
if( Object.prototype.hasOwnProperty.call( jdata, key ) )
{
value = jdata[key];
//prefer console.log here...
alert( 'key: ' + key + ', value: ' + value)
}
}
}
$( function()
{
$( '#run' ).click( function()
{
parse_json();
} );
} );
Demo: http://jsfiddle.net/hjVqf/
Ok, I've been fooling around with this on jsfiddle. One of the things I noticed that you weren't doing, was returning a value for the reviver function. According to the Microsoft JSON.parse docs, the point of the function is to return a modified (if necessary) version of the value property which will update the DOM object. Now, it also says that:
A function that filters and transforms
the results. The deserialized object
is traversed recursively, and the
reviver function is called for each
member of the object in post-order
(every object is revived after all its
members have been revived).
Ok, so I think the key here is that the reason the function is run twice, is because it's running for the first member (simply "caller": "539293493") and then for the object itself ({"caller": "539293493"}).
You'll notice that in my linked example, with the added return value; statement, the object with the blank key is the whole object.

Categories