Get first item from comma delimited object - javascript

Hi I have an object rowObject passed into a javascript function. When I inspect it by putting it into an alert I see something like:
435,345,345345,56456
What I want to achieve is to get the first integer ie. 435 from the list.
I know how to do this in server side code but client side code.
Can someone please help me with this?

Assuming that your rowObject is a string, you can use .split() to split the comma delimited list. At this point you can access the array of items by index and get the first element.
http://www.w3schools.com/jsref/jsref_split.asp
An Example
var rowObject = "435,345,345345,56456";
var splitRowObject = rowObject.split(',');
if(splitRowObject.length > 0)
alert(splitRowObject[0]);

alert() is calling objects toString() method, so you don't know the structure of the object. It is a good idea to use console.log instead for logging objects as in modern browsers it will allow you to explore structure of the object in the console window.
One of the solutions you can do without knowing the structure is:
var firstInteger = +rowObject.toString().split(',')[0] // 435
That works if rowObject is string, array or everything else :).
EDIT: Putting + before the string will try to convert it to a number.

Have you tried rowObject[0]?

The fact that the alert shows 435,345,345345,56456 doesn't mean that the object is string, it could be Object and Array as well as their toString method implemented to display it in such way. For example the native array is also looks like that when alerting or converting to string, so you need to call toString method at first then split it by comma:
var firstInt = rowObject.toString().split(',')[0];

Related

getComputedStyle Font Family returns multiple families [duplicate]

Hi I have an object rowObject passed into a javascript function. When I inspect it by putting it into an alert I see something like:
435,345,345345,56456
What I want to achieve is to get the first integer ie. 435 from the list.
I know how to do this in server side code but client side code.
Can someone please help me with this?
Assuming that your rowObject is a string, you can use .split() to split the comma delimited list. At this point you can access the array of items by index and get the first element.
http://www.w3schools.com/jsref/jsref_split.asp
An Example
var rowObject = "435,345,345345,56456";
var splitRowObject = rowObject.split(',');
if(splitRowObject.length > 0)
alert(splitRowObject[0]);
alert() is calling objects toString() method, so you don't know the structure of the object. It is a good idea to use console.log instead for logging objects as in modern browsers it will allow you to explore structure of the object in the console window.
One of the solutions you can do without knowing the structure is:
var firstInteger = +rowObject.toString().split(',')[0] // 435
That works if rowObject is string, array or everything else :).
EDIT: Putting + before the string will try to convert it to a number.
Have you tried rowObject[0]?
The fact that the alert shows 435,345,345345,56456 doesn't mean that the object is string, it could be Object and Array as well as their toString method implemented to display it in such way. For example the native array is also looks like that when alerting or converting to string, so you need to call toString method at first then split it by comma:
var firstInt = rowObject.toString().split(',')[0];

How to parse the following json string into an object?

var jsonString = '{"DeviceId":3,"results":{"1":"[{\"x\":513,\"y\":565,\"width\":175,\"hight\":208}]"}}';
var message = JSON.parse(jsonString);
I got an error saying Unexpected token u in JSON at position 0
at JSON.parse.
Could you please guide me what's wrong?
THanks in advance!
At the last few characters looks wrong. The :212 has no sense as the value (that long array) for key "1" was already set, so that later :212 looks weird
Also enclosing it in single quotes it makes that all be like a huge string, and not as an array structure.
See Results key as value contains a sub array which contain "1" key which as value contains a string enclosing another json array (but escaped as plain string, so no structurally accesible for the main object . But that string if post -processed the :212 is paired to what? , no key, no comma neighter , to the precedent whole array which already was the value, not the key?. Anyway weird.
In your JSON string, there is wrong something with ":212", as it's not valid JSON, because it doesn't have any property that it's mapping the value for. For example, you are mapping values for width and height with properties keys. But for "212", there is no property.
Here is the above JSON formatted:
var jsonString = '{"DeviceId":"3","results":{"1":"[{\\"x\\":513,\\"y\\":565,\\"width\\":175,\\"hight\\":208}]"}}'
var message = JSON.parse(jsonString);
If you want to format the results, you can do to it, there is no error on it:
JSON.parse(message.results['1'])
Here is the JS Bin link for above code: https://jsbin.com/fiyeyet/edit?js,console
Just an advice
Professional code is all about proper spacing, proper identation , proper commenting, don't try to write down all within one single line, structure it VISUALLY nice to see nice to read nice to comprehend, and you will be approved in most jobs.
Hint: declare a normal array/object , convert it to json string using the proper function, then use the string variable returned by the function to test your code or whatever doing. That way, you can write down in the source really nice the structure.

append object to innerHTML and get that object from innerHTML

here is an example in jsfiddle.
I want to know if I can append a javascript object to innerHTML, that get that object again from innerHTML as object.
something like,
alert((this.innerHTML).html);
that's just an example, don't ask me why do you need this?
I'm trying to edit an existing code, and I have to do this so.
I have to transfer an object via div.innerHTML.
Check this jsfiddle. In it, I add the object to the div as a 'data-'-attribute, using JSON to convert it to a string. After that, adding some comment to the div triggers the DOMSubtreeModified-handler, in which the 'html'-part of the object is retrieved and alerted. It that something to work with?
In this case, quite possible your only option is to convert your object to string and then put that into the element. (This is done by looping through the key, values building the string as you go.)
You would reverse the process to convert it back into an obj.
I know some javascript libary's have helper functions to make this process very simple.
You could try adding the data directly onto the dom element, rather than as its content..
tempDiv.objData = myObject;
It was suggested to use JSON, but no code. So:
function addObjAsJSON(el, obj) {
el.setAttribute('data-myJSON', encodeURIComponent(JSON.stringify(obj)));
}
function getObjAsJSON(el) {
return JSON.parse(decodeURIComponent(el.getAttribute('data-myJSON')));
}
That should allow you to add anything as a serialised object, then get it back. You should add some error checking to make it robust though (e.g. check that you get a string back from the call to getAttribute).
For user agents that don't have built-in JSON support, see json.org which has a link in the javascript section to json.js.

passing a variable into a json collection

I'm trying to call the following js method. I wish to pass in the variable siteid. I can alert this value. But it doesn't seem to work in the following context. ie if just add the id 1234 it works.
alert(siteid);
embedSWF ('flashcontent', '{"siteID":siteid,"siteType":"portal","mainSWF":"http:\/\/tv.xxx.net\/flash\/xxx1.swf","movieWidth":"426","movieHeight":"276","expressInstall":"http:\/\/tv.xxx.net\/expressInstall.swf"}');
You need to concatenate the value of siteid into your string: '...' + siteid + '...'
Depending on what you're building, you may want the string to have quotes around the value.
The most robust way to do this is to first make the object as a normal object and then serialize it:
var parms = {siteID: siteid, siteType: "portal", ...};
embedSWF('flashcontent', JSON.stringify(parms));
If you need to support outdated browsers that don't have the built-in JSON object, there are several implementations available online.
embedSWF ('flashcontent', '{"siteID":'+siteid+',"siteType":"portal","mainSWF":"http:\/\/tv.xxx.net\/flash\/xxx1.swf","movieWidth":"426","movieHeight":"276","expressInstall":"http:\/\/tv.xxx.net\/expressInstall.swf"}');
You're passing a string:
'{"siteID":siteid,"siteType":"portal","mainSWF":"http:\/\/tv.xxx.net\/flash\/xxx1.swf","movieWidth":"426","movieHeight":"276","expressInstall":"http:\/\/tv.xxx.net\/expressInstall.swf"}'
You probably mean to pass:
'{"siteID":' + siteid + ',"siteType":"portal","mainSWF":"http:\/\/tv.xxx.net\/flash\/xxx1.swf","movieWidth":"426","movieHeight":"276","expressInstall":"http:\/\/tv.xxx.net\/expressInstall.swf"}');
It seems a little weird to pass a JSON string, rather than the associative array itself. Either way, that's your problem, above.

Javascript: How can you get a single element out of an array and make a string from it

I am new to javascript and was trying something in an exercise for school.
I have an array with some javascript elements.
This is the array:
var testObjecten = [
window.walkTheDog,
window.focus,
document.images,
document.layers,
document.all,
document.getElementById,
document.getElementsByTagName,
document.styleSheets,
document.createElement,
document.createTreeWalker,
document.implementation.createDocument,
window.ActiveXObject,
window.XMLHttpRequest
];
My objective is to test them for support in the browser and return yes or no.
I know how to get to the correct result but I cannot do some things needed for it.
I have created a table with Javascript. In the first part of the table must come a TextNode with the full name of the element. So I was trying to convert the element to string but it does not seem to work.
I know you can convert an array to one big string with join but how can you do this with an element?
Also on a related question: If the same array would contain strings with the elements above (with "" around them) would it still be possible to test with them?
I know you can convert an array to one big string with join but how can you do this with an element?
Javascript does also know the method '.toString()'. Perhaps it will work.
Also on a related question: If the same array would contain strings with the elements above (with "" around them) would it still be possible to test with them?
In Javascript exists the method '.eval()'. This one is primitiv but very powerful.
for(var i=0; i<testObjecten.length;i++){
if(testObjecten[i]==null){
alert("not Supported");
}
}
the objects are automatically converted to String using toString() method.
you can save names of your elements in separate array with same indexes and then output it.
I'm not quite sure what your attempting but this might help.
var testObjecten = {
"window.walkTheDog": window.walkTheDog,
"window.focus": window.focu,
...
};
var names = [];
for (var key in testObjecten) {
o.push(key);
}
document.createTextNode(names[i]);
The problem with trying to use toString is that you get things like HTMLElement or other data you do not actually care about. I believe you wanted to print the strings "window.walkTheDog", etc.
There is no easy way of getting this data without having the physical strings somewhere.

Categories

Resources