Get value from json object without count the array number - javascript

This is my json object i want to get alert it without the array order like[0], [1].
var jsononj = {
"objnew" :
[{testarry: "thi is my demo text" },
{testarry2: "thi is my demo text2" }
] };
}
var newtest = jsononj.objnew[0].testarry;
alert(newtest);
i want to alert without [0]. how to i achieve this

I think this is what you're looking for:
var i;
for (i = 0; i < jsonobj.objnew.length; i++) {
if (jsonobj.objnew[i].testarry) {
alert(jsonobj.objnew[i].testarry);
}
}

This is just stupid but I removed the [0]
var jsononj = {
"objnew" : [
{testarry: "thi is my demo text" },
{testarry2: "thi is my demo text2" }
]
};
var a = jsononj.objnew.shift();
alert(a.testarry);
jsononj.objnew.unshift(a);

That's not JSON, that's a Javascript object. JSON is a text format for representing data.
If you want to look for an object with a specific property, loop through the objects in the array and check for it:
var newtest = null;
for (var i = 0; i < jsononj.objnew.length; i++) {
var obj = jsononj.objnew[i];
if (obj.hasOwnProperty('testarry') {
newtest = obj.testarry;
break;
}
}
if (newtest != null) {
// found one
}

doing a var firstOne = jsononj.objnew[0];
but if you simply don't like the [0] through your lines, extend the Array prototype
Array.prototype.first = function () {
return this[0];
};
var newtest = jsononj.objnew.first().testarry;
alert(newtest);
more info at First element in array - jQuery

Related

Accessing dynamic values from JSON object in javascript

this is my json object. i need to get only all the values of packageName and assign it to an array. can any body help me with that. i can not go for using indexes since this is dynamic object.
thanks in advance.
var data = [
{
"packageName":"string",
"packageValue":"string"
},
{
"packageName":"string",
"packageValue":"string"
}
]
Use javascript map function
var packageNames = data.map(function(obj){
return obj.packageName;
})
var data=[
{
"packageName":"string1",
"packageValue":"string"
},
{
"packageName":"string2",
"packageValue":"string"
}
]
var packageNames = data.map(function(obj){
return obj.packageName;
})
console.log(packageNames)
You can use filter function and add to array only when this key exists.
var arr = [];
data.filter(getValue)
function getValue(data){
if(data[packageName]){
arr.push(data[packageName])
}
}
You can add an if statement to check the key and then push it to an array.
for(var i = 0; i< data.length; i++){
for (var property in data[i]) {
if (data[i].hasOwnProperty(property)) {
console.log(property);
console.log(data[i][property]);
}
}
}

Javascript : Select Element in URL with multiple instance of the same element

i need to retrieve a value from an URL in JS, my problem is in this url, the element is repeated at least twice with different value. What i need is the last one.
Example :
http://randomsite.com/index.php?element1=random1&element2=random2&element1=random3
and what i want is "random3" and NOT "random1"
I've tried url.match(/.(\&|\?)element1=(.?)\&/)[2];
But it always gives me the first one :(
I don't have the possibility to change how the url is written as this is for a browser extension.
var ws = "http://randomsite.com/index.php?element1=random1&element2=random2&element1=random3",
input = ws.split("?")[1].split("&"),
dataset = {},
val_to_find = "element1";
for ( var item in input){
var d = input[item].split("=");
if (!dataset[d[0]]){ dataset[d[0]] = new Array(); dataset[d[0]].push(d[1]); }
else{
dataset[d[0]].push(d[1]);
}
}
console.log("item: ", dataset[val_to_find][dataset[val_to_find].length -1]);
return dataset[val_to_find][dataset[val_to_find].length -1];
http://jsfiddle.net/wMuHW/
Take the minimum value (other than -1) from urlString.lastIndexOf("&element1=") and urlString.lastIndexOf("?element1="), then use urlString.substring.
Or alternately, split the string up:
var parts = urlString.split(/[?&]/);
...which will give you:
[
"http://randomsite.com/index.php",
"element1=random1",
"element2=random2",
"element1=random3"
]
...then start looping from the end of the array finding the first entry that starts with element= and grabbing the bit after the = (again with substring).
You could;
for (var result, match, re = /[&?]element1=(.+?)(\&|$)/g; match = re.exec(url);) {
result = match[1];
}
alert(result);
Id try keeping a nested array of duplicate elements
function parseQueryString() {
var elements = {},
query = window.location.search.substring(1),
vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('='),
key = decodeURIComponent(pair[0]),
value = decodeURIComponent(pair[1]);
if (elements.hasOwnProperty(key)) {
elements[key].push(value);
}
else {
elements[key] = [value];
}
}
}
Used on: www.example.com?element1=hello&element2=test&element1=more
Would give you the object:
{
element1: [
"hello",
"more"
],
element2:[
"test"
]
}

how to get length of json encoded array in javascript?

I have a json encoded array like this:
{
"ar0":"{\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}",
"ar1":"{\"start\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"end\":{\"lat\":23.0420584,\"lng\":72.67145549999998},\"waypoints\":[[23.02237,72.6500747]]}",
"ar2":"{\"start\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"end\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"waypoints\":[[23.0016629,72.58898380000005]]}"
}
my quetion is :
(1) How to find length of this array? //here it is 3
(2) How to use it's value?
//for example:for as0 the value is {\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}
javascript code where i use upper things :
function setroute(os)
{
var wp = [];
for(var i=0;i<os.waypoints.length;i++)
wp[i] = {'location': new google.maps.LatLng(os.waypoints[i][0], os.waypoints[i][1]),'stopover':false }
ser.route({'origin':new google.maps.LatLng(os.start.lat,os.start.lng),
'destination':new google.maps.LatLng(os.end.lat,os.end.lng),
'waypoints': wp,
'travelMode': google.maps.DirectionsTravelMode.DRIVING},function(res,sts) {
if(sts=='OK')ren.setDirections(res);
})
}
function fetchdata()
{
var jax = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
jax.open('POST','process.php');
jax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
jax.send('command=fetch')
jax.onreadystatechange = function(){ if(jax.readyState==4) {
alert(JSON.parse(jax.responseText).ar0);
try {
console.log(jax.responseText);
//it is not work
for(var i=0;i<JSON.parse(jax.responseText).length;i++)
{
setroute( eval('(' + jax.responseText + ')') );
}
}
catch(e){ alert(e); }
}}
}
Your JSON is not an array, but an object. If you want it to be an array, it should be something like this:
[
"{\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}",
"{\"start\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"end\":{\"lat\":23.0420584,\"lng\":72.67145549999998},\"waypoints\":[[23.02237,72.6500747]]}",
"{\"start\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"end\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"waypoints\":[[23.0016629,72.58898380000005]]}"
]
Then, you can get a javascript array as follows:
var array = JSON.parse(jax.responseText);
And access values as follows:
array[0]
array.length
EDIT: In order to have a real JSON array with the PHP json_encode method, see this related question.
With this modification you will be able to use all the possibilities of JS array without workaround.
Objects in JavaScript don't have a .length property like Arrays do.
In ES5 you can do: Object.keys({}).length; // 0
The other solution would be to loop over all the properties of your object with a for .. in loop and count.
You can use the following code. It will produce your desired output 3
var test = {
"ar0":"{\"start\":{\"lat\":22.9939202,\"lng\":72.50009499999999},\"end\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"waypoints\":[[23.0316834,72.4779436]]}",
"ar1":"{\"start\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"end\":{\"lat\":23.0420584,\"lng\":72.67145549999998},\"waypoints\":[[23.02237,72.6500747]]}",
"ar2":"{\"start\":{\"lat\":23.0394491,\"lng\":72.51248850000002},\"end\":{\"lat\":22.9999061,\"lng\":72.65318300000001},\"waypoints\":[[23.0016629,72.58898380000005]]}"
}
var getLength = function(obj) {
var i = 0, key;
for (key in obj) {
if (obj.hasOwnProperty(key)){
i++;
}
}
return i;
};
console.log(getLength(test));
For your first question, you should use Object.keys(item).length
To get the values of your object, you should iterate over it with a for loop:
for(var key in item)
{
var val = item[key];
}
var count = 0;
Object.keys(json).forEach(function (key) {
count++;
alert(json[key].start.lat);
});
alert(count);
Using jQuery
$(json).each(function() { count++; alert(this.start.lat); });
alert(count);

Javascript table string to array

I have a string that looks like:
<tr><td>Date</td><td>Value</td></tr>
<tr><td>2013-01-01</td><td>231.198</td></tr>
<tr><td>2013-02-01</td><td>232.770</td></tr>
<tr><td>2013-03-01</td><td>232.340</td></tr>
<tr><td>2013-04-01</td><td>231.485</td></tr>
<tr><td>2013-05-01</td><td>231.831</td></tr>
<tr><td>2013-06-01</td><td>232.944</td></tr>
<tr><td>2013-07-01</td><td>233.318</td></tr>
...which is of course essentially a table.
I'd like to dynamically convert this string into an array containing 2 arrays. One of dates, one of values.
[Edited in]
An array of objects with date and values would work too.
The following::
var input = // your string
var output = $(input).slice(1).map(function(i,el) {
var tds = $(el).find("td");
return { "date" : tds.eq(0).text(), "value" : tds.eq(1).text() };
}).get();
...will return an array of objects in this format:
[{"date":"2013-01-01","value":"231.198"}, {"date":"2013-02-01","value":"232.770"}, ... ]
If you'd like each value to be treated as a number you can convert it like so:
return { "date" : tds.eq(0).text(), "value" : +tds.eq(1).text() };
// add the unary plus operator ---------------^
Then the result will be:
[{"date":"2013-01-01","value":231.198}, {"date":"2013-02-01","value":232.77}, ... ]
While you've already accepted an answer, I thought I'd post a plain JavaScript solution (albeit largely because I spent time working on it, before Barmar pointed out that you're willing and able to use jQuery):
function cellContents(htmlStr, what) {
var _table = document.createElement('table');
_table.innerHTML = htmlStr;
var rows = _table.getElementsByTagName('tr'),
text = 'textContent' in document ? 'textContent' : 'innerText',
cells,
matches = {};
for (var w = 0, wL = what.length; w < wL; w++) {
matches[what[w]] = [];
for (var r = 1, rL = rows.length; r < rL; r++) {
cells = rows[r].getElementsByTagName('td');
matches[what[w]].push(cells[w][text]);
}
}
return matches;
}
var str = "<tr><td>Date</td><td>Value</td></tr><tr><td>2013-01-01</td><td>231.198</td></tr><tr><td>2013-02-01</td><td>232.770</td></tr><tr><td>2013-03-01</td><td>232.340</td></tr><tr><td>2013-04-01</td><td>231.485</td></tr><tr><td>2013-05-01</td><td>231.831</td></tr><tr><td>2013-06-01</td><td>232.944</td></tr><tr><td>2013-07-01</td><td>233.318</td></tr>";
console.log(cellContents(str, ['dates', 'values']));
JS Fiddle demo.
For a pure JavaScript solution you can try something like this (assuming str holds your string) :
var arrStr = str.replace(/<td>/g, "").replace(/<tr>/g, "").split("</td></tr>");
var arrObj = [];
var arrData
for (var i = 1; i < arrStr.length - 1; i++) {
arrData = arrStr[i].split("</td>");
arrObj.push({ Date: arrData[0], Value: arrData[1] })
}
It's a burte-force string replacement/split, but at the end arrObj will have array of objects.
if its a valid html table structure, wrap it between table tags, and use jquery to parse it.
then use jquery's selectors to find the columns.
e.g something like this ( pseudo code, havent tried it )
table = $(yourTableString);
dates = table.find("tr td:nth-child(1)");
values = table.find("tr td:nth-child(2)");
Using jQuery:
var table = $('<table>'+str+'</table>');
var result = {};
table.find('tr:gt(0)').each(function () {
var date = $(this).find("td:nth-child(1)").text();
var value = $(this).find("td:nth-child(2)").text();
result[date] = value;
}
:gt(0) is to skip over the header line. This will create an associative array object that maps dates to values. Assuming the dates are unique, this is likely to be more useful than two arrays or an array of objects.

Looking inside an object for a specific string using JavaScript

On JavaScript, I have the following JSON:
var mJSON = {
"monster":[
{"id":"150","name":"Richard"},
{"id":"100","name":"Gregory"},
{"id":"200","name":"Rachel"},
{"id":"250","name":"Mike"}
]
}
I need to refine this object by a string inputted by the user. For example: "100".
The result should be a new JSON like this:
var zJSON = {
"monster":[
{"id":"100","name":"Gregory"}
]
}
I tried looking in Google on easy ways to run through a JavaScript object searching for a string, but without success. There's nothing like jQuery's $.inArray too, as far I know. Anyone has any idea?
I'm thinking about converting this JSON into a string, grep it for the value inputted by the user, and then converting the string to JSON again, but I think this will be too troublesome for something that could be easy to achieve.
How about using $.map?
var id = 100;
var result = $.map(monsters, function(monster){
return monster.id == id ? monster : null;
});
JQuery.map() applies function to each argument of the array (monsters) and produces the new array that contains the values returned by the function. What is important in this case is that if function returns null then the element is removed from the resulting array.
EDIT:
As #Jan has kindly suggested in his comment $.grep suits even better! Here is the code example for your monsters:
var id = 100;
var result = $.grep(monsters, function(monster){
return monster.id == id;
});
Why don't you just loop through the array removing stuff that doesn't match?
Without using libraries, you could do something like this:
var mJSON = {
"monster":[
{"id":"150","name":"Richard"},
{"id":"100","name":"Gregory"},
{"id":"200","name":"Rachel"},
{"id":"250","name":"Mike"}
]
};
var searchTerm = "100";
var result = mJSON.monster.filter(function(e){
// if you want loose(r) searches, you could use a regex here
// rather than explicit equality
if(e.id == searchTerm)
{
return true;
}
});
console.log(result);
http://jsfiddle.net/dbrecht/MZQzM/
Use the grep method. Example:
var obj = {
monster: [
{ id: "150", name: "Richard" },
{ id: "100", name: "Gregory" },
{ id: "200", name: "Rachel" },
{ id: "250", name: "Mike" }
]
};
var input = "100";
var filtered = {
monster: $.grep(obj.monster, function(e){
return e.id == input;
})
};
var mJSON = {
"monster":[
{"id":"150","name":"Richard"},
{"id":"100","name":"Gregory"},
{"id":"200","name":"Rachel"},
{"id":"250","name":"Mike"}
]
};
var searhKey = "100";
var found = false, i = 0, pos = -1, l = MJSON.monster.length;
while(!found && i < l) {
if(MJSON.monster[i].id == searchKey) {
pos = i;
found = true;
}
i += 1;
}
if(found) {
alert(pos);
} else {
alert("not found");
}

Categories

Resources