Get value from json string using key's value [duplicate] - javascript

This question already has answers here:
How to find an appropriate object in array by one of its properties
(3 answers)
Closed 6 years ago.
Hi I have a json string
"{"data":[{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":15,"ConfigName":"Offline Days","ConfigValue":"Sunday"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}]}"
I want to check ConfigValue of ConfigName "CurrentTime".
Currently I am accessing it by below code
var d = JSON.parse(data).data;
d[2].ConfigValue
but sometimes the json string will be
"{"data":[{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}]}"
according to above string now if i want to access "CurrentTime"
I will have to write below code
var d = JSON.parse(data).data;
d[1].ConfigValue
So can anyone tell how to access it? Because the array may change anytime so I cannot hardcode the array index like that.

You can run a loop and check the value of ConfigName. Below is the code
var data = '{"data":[{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":15,"ConfigName":"Offline Days","ConfigValue":"Sunday"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}]}';
var d = JSON.parse(data).data;
for(var i=0; i<d.length; i++)
{
if(d[i].ConfigName === 'CurrentTime')
{
alert(d[i].ConfigValue); //Do stuff with the value.
}
}

You have same quotes inside and outside string without escaping. But maybe it takes place only in question texts.
In this case You need to check every item like this:
for (var i in d) {
if (d[i].Id == 0) {
alert(d[i].ConfigName);
}
}

You can try this:
var k = {"data":[{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":15,"ConfigName":"Offline Days","ConfigValue":"Sunday"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}]}
var result = $(jQuery.parseJSON(JSON.stringify(k))).each(function() {
var configName = this.ConfigName;
var configValue = this.ConfigValue;
});
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You first need to find the object in the array with "ConfigValue" equal to "CurrentTime". Once you have this object, you can simply access its "CongigValue" property.
var json1 = {"data":
[
{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":15,"ConfigName":"Offline Days","ConfigValue":"Sunday"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}
]
};
var json2 = {"data":
[
{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}
]
};
var currentTime = findCurrentTime( json1 );
console.log( "currentTime: " + currentTime );
var currentTime = findCurrentTime( json2 );
console.log( "currentTime: " + currentTime );
function findCurrentTime( jsonObj )
{
var filteredArray = jsonObj.data.filter(function(element){
return element.ConfigName === "CurrentTime";
});//filter()
if( filteredArray.length > 0 )
return filteredArray[0].ConfigValue;
return false;
}//findCurrentTime()

Related

Javascript Appending to 2-D Array

I am trying to append an array to an array. I am expecting the output to be something like:
[[Dep,POR],[14073,99.25],[14072,0.06]]
But I am getting:
Dep,POR,14073,99.25,14072,0.06
Here's what I have so far:
function get_historical() {
var well = document.getElementById('wellSelect');
var selected_well = well.options[well.selectedIndex].value;
var hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
hist_por = ['Dep','POR'];
for (var item in hist_json_obj) {
if (hist_json_obj.hasOwnProperty(item)) {
var dep = hist_json_obj[item].dep;
var por = hist_json_obj[item].por;
var arr_por = [dep, parseFloat(por)];
hist_por.push(arr_por);
}
}
document.write(hist_por);
}
When you initialize hist_por, you want that to be a 2-D array whereas you currently have just a single array. So you would want to change its instantiation to:
hist_por = [['Dep','POR']]; // [[ ... ]] instead of [ ... ]
Also per #justrusty's answer, you need to JSON.stringify(hist_por) when you pass it to document.write(). This is the more important piece so his answer should be accepted.
So the whole code block would become:
function get_historical() {
var well = document.getElementById('wellSelect');
var selected_well = well.options[well.selectedIndex].value;
var hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
hist_por = [['Dep','POR']];
for (var item in hist_json_obj) {
if (hist_json_obj.hasOwnProperty(item)) {
var dep = hist_json_obj[item].dep;
var por = hist_json_obj[item].por;
var arr_rop = [dep, parseFloat(por)];
hist_por.push(arr_por);
}
}
document.write(JSON.stringify(hist_por));
}
This may help you https://codepen.io/anon/pen/xQLzXx
var arr = ['foo','bar'];
var arr2 = ['baz', 'boo']
arr.push(arr2);
console.log(arr);
document.write(arr);
document.write("<br>");
document.write(JSON.stringify(arr));
It's basically just the way it writes it to document. If you log it in console you'll see the array appended. Or if you JSON.stringify() first it will show as you expect.
My advice is ALWAYS console.log() so you can see exactly how the data is structured
The others have already pointed out what the problem is (+ there's a typo in one of your variable names - arr_rop vs arr_por). Here's an ES6 version that will break in older browsers, for learning purposes:
function get_historical() {
const well = document.getElementById('wellSelect');
const selected_well = well.options[well.selectedIndex].value;
const hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
const hist_por = Object.values(hist_json_obj).reduce(
(arr, item) => [...arr, [item.dep, +item.por]],
[["Dep", "POR"]]
);
document.write(JSON.stringify(hist_por));
}

JS - Associative arrays [duplicate]

This question already has answers here:
Why does a string index in an array not increase the 'length'?
(7 answers)
Closed 7 years ago.
Demo
Why does associative array qaObj return 0 length?
$(function(){
var data = "Q$:I am in.A$: out Q$:whats this A$:Answer";
alert("in");
var str = $.trim(data).replace(/(\r\n|\n|\r)/gm,"");
var qaObj = new Array();
if(str != null && str.indexOf("A$:") != -1 && str.indexOf("Q$:") != -1){
var qaPairs = str.split("Q$:"); /**Eliminate first header part**/
qaPairs.shift();
alert(qaPairs);
for(var counter = 0; counter < qaPairs.length; counter++){
var qaSplittedArr = qaPairs[counter].split("A$:");
qaObj[qaSplittedArr[0]] = qaSplittedArr[1];
}
}
alert(qaObj);
alert(qaObj["I am in."]);
});
I am not able to send qaObj to php. It shows empty array. So I am not able to loop through.
Why is it happening?
I am sending through ajax.
qaObj needs to be an object ({}) here, not an array (new Array()). JavaScript objects are the equivalents of PHP's associative arrays. Updated fiddle: http://jsfiddle.net/p6p8jezu/4/
$(function(){
var data = "Q$:I am in.A$: out Q$:whats this A$:Answer";
var str = $.trim(data).replace(/(\r\n|\n|\r)/gm,"");
var qaObj = {};
if(str != null && str.indexOf("A$:") != -1 && str.indexOf("Q$:") != -1){
var qaPairs = str.split("Q$:"); /**Eliminate first header part**/
qaPairs.shift();
alert(qaPairs);
for(var counter = 0; counter < qaPairs.length; counter++){
var qaSplittedArr = qaPairs[counter].split("A$:");
qaObj[qaSplittedArr[0]] = qaSplittedArr[1];
}
}
alert(JSON.stringify(qaObj));
alert(qaObj["I am in."]);
});
Try making use of pure Javascript objects instead of arrays.
Change the new Array() to {} in order to make an object.
var qaObj = {};
Now you can do your favorite PHP-like associative array assignment on this object as such and achieve the desired result:
qaObj[qaSplittedArr[0]] = qaSplittedArr[1];
Check your console in this DEMO.
Note that the recommended approach to insert elements to an array is to use .push() method, and not as PHP-like syntax that you've used.

Loading an array from local storage: result not an array - javascript [duplicate]

This question already has answers here:
How to store objects in HTML5 localStorage/sessionStorage
(24 answers)
Closed 8 years ago.
I have several large multi-dimensional arrays that I'm saving to local storage. They look like this:
[[[-150],[0],[-650],0],[[-100],[0],[-650],0],[[-50],[0],[-650],0] ... ]
The data is '4D' data. When I try loading this 'string' into an array in another JS (in separate html), it doesn't behave like an array- it's only a string.
Here's how I load the data back into the second JS (not sure why the loop didn't work either):
var lay= new Array();
//for(var g=0;g>=9;g++)
//{ lay[g] = localStorage.getItem("key" + g);
// console.log(lay[g]);
//}
lay[0] = localStorage.getItem("key0");
lay[1] = localStorage.getItem("key1");
lay[2] = localStorage.getItem("key2");
//... more here
lay[9] = localStorage.getItem("key3");
After I load this "4D" info into the array, I pull the info out to use it:
var count=0;
var len=0;
for (y=0;y<=1;y++)
{ console.log(lay[y]);
count=1;
len = lay[y].length;
for (x=1;x<=len-1;x++)
{
Rx = lay[y][count][0];
Ry = lay[y][count][1];
Rz = lay[y][count][2];
Rcolor = lay[y][count][3];
When I add this to the code console.log(len); I get the length of characters in the array, not the number of elements. How can I get the data from local storage to come in and behave like array? I thought that the formatting alone would get it behave like an array.
Do I need to parse it back into an array again? If so, I'm guessing I should just output the data in a simpler format to parse it again...
Thanks for the help!
Edit
Here's how I made the local storage:
for (var a=0;a<=14;a++)
{ updateTemp(tStep + a);
$("#temp tbody tr").each(function(i, v){
data[i] = Array();
$(this).children('td').each(function(ii, vv){
data[i][ii] = $(this).text();
rows=ii;
cols=i;
});
});
retval="";
for (var q=0;q<=cols;q++)
{
for (var w=0;w<=rows;w++)
{
var tempv = data[q][w];
var tX = w*50 - 1000;
var tY = 1*50 - 50;
var tZ = q*50 - 1000;
if (tempv==-9){
(dummy=q*w);
}
else {retval += tX +',' + tY + ',' + tZ + ',' + tempv + ',';}
}
}
var kee = "key" + a;
retval = retval.substring(0, retval.length-1); //this is to get rid of the last character which is an extra ,
window.localStorage.setItem(kee, retval);}
JSON encode the array before storing, parse after retrieving.
localStorage.test = JSON.stringify([1,2,3]);
console.log(JSON.parse(localStorage.test));
This is a duplicate of “Storing Objects in HTML5 localStorage”. localstorage only handles strings. As suggested there, serialise your array to a JSON string before storing.

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.

Categories

Resources