Javascript, Lodash, Underscore change value of Array - javascript

May be a duplicate but read alot on here on how to achieve the following and couldn't get it to do exactly what I need. Read: Javascript array Link2 link3
I have a large array (short sample provided below) and would like to format the REPORT_DATE value so that instead of for example "31/05/2015 00:00:00" I get 31/05/2015. Does anyone know of an easy way to do this ?
{["data":[{"DOC1":"1234","FILE_NAME":"4321.PDF","TITLE":"gwewrgw","REPORT_DATE":"31/05/2015 00:00:00","CLIENT_ID":"1234512","CLIENT_NAME":"Zuba"}
,{"DOC1":"4737","FILE_NAME":"52345.PDF","TITLE":"erywery","REPORT_DATE":"30/09/2015 00:00:00","CLIENT_ID":"5234523","CLIENT_NAME":"Ziba"}
,{"DOC1":"1234","FILE_NAME":"452345.PDF","TITLE":"wgrwrg","REPORT_DATE":"31/05/2015 00:00:00","CLIENT_ID":"23452345","CLIENT_NAME":"Zuba"}
,{"DOC1":"4737","FILE_NAME":"2345234.PDF","TITLE":"wegwerg","REPORT_DATE":"30/09/2015 00:00:00","CLIENT_ID":"4523452","CLIENT_NAME":"Ziba"}
,{"DOC1":"4737","FILE_NAME":"52342345.PDF","TITLE":"egwergw","REPORT_DATE":"30/09/2015 00:00:00","CLIENT_ID":"43532452","CLIENT_NAME":"Ziba"}],"pagination":{"ItemsPerPage":"5","IntervalFrom":"1","IntervalTo":"5","TotalPages":"14","TotalItems":"68","CurrentPage":"1","pageSizes":[{"name":"5","items":5},{"name":"10","items":10},{"name":"25","items":25},{"name":"50","items":50},{"name":"100","items":100}],"maxSize":5}}
[
Appreciate the help....

you pasted a bad-formatted snippet, by the way, you can modify an array using `Array.prototype.map' if you don't need for the memory reference
"use strict";
var data = [{"DOC1":"1234","FILE_NAME":"4321.PDF","TITLE":"gwewrgw","REPORT_DATE":"31/05/2015 00:00:00","CLIENT_ID":"1234512","CLIENT_NAME":"Zuba"}];
var result = data.map(i => {
i.REPORT_DATE = Date.apply(null, i.REPORT_DATE.split(' ').reverse());
return i;
});
console.log(result)

Related

JSON array returns undefined unless presented as a var in javascript

I know that there are many questions like this one but none match the problem I am having.
I am trying to parse a JSON array passed from my php, I can access the JSON array but only at the top level. After that I get an undefined error.
The survey_data JSON
{test: "{"title":"test","data":{"questions":{"test":{"name":"test","type":"text","options":",,"}}}}", The New Survey: "{"title":"The New Survey","data":{"questions":{"te…":{"name":"test","type":"text","options":",,"}}}}"}
Here is my JS code
var survey_data = <?php echo json_encode($survey_data); ?>;
$(document).on( "click", ".view", function() {
var survey_name = $(this).closest('tr').find(".quest-name-list").text();
console.log(survey_data[survey_name]['title']);
});
If I run console.log(survey_data[survey_name]); I get the JSON
{"title":"test","data":{"questions":{"test":{"name":"test","type":"text","options":",,"}}}}
But the above console.log(survey_data[survey_name]['title']); returns undefined
If I run the below code though it works
var json = {"title":"test","data":{"questions":{"test":{"name":"test","type":"text","options":",,"}}}};
console.log(survey_data[survey_name]['title']);
This will return the desired JSON field, I can not figure out why though.
Any help is appreciated!
EDIT: Thanks to everyone who helped me walk through the problem, here is the problem and fix.
In my php code I had
$survey_data = [];
foreach ($surveys as $survey) {
$survey_fi = $survey['survey_fields'];
$survey_data[ $survey_f['title']] = imap_base64($survey_fi);
}
But the field($survey_fi) that I was adding to the array was already JSON, so I needed to decode the JSON first and then add it the array that would be converted back to JSON in my JS code.
This is the solution
$survey_data = [];
foreach ($surveys as $survey) {
$survey_fi = $survey['survey_fields'];
$survey_f = json_decode(imap_base64($survey_fi), true);
$survey_data[ $survey_f['title']] = $survey_f;
}
I think survey_data[survey_name] is JSON string and there won't be any title property for a string so parse it before trying to get the property.
console.log(JSON.parse(survey_data[survey_name])['title']);

Having trouble referring to object within array

I am trying to write an html page for class that uses a drop down menu to allow users to pull up a list of relevant information. Unfortunately I am having trouble figuring out how to make the script call on the information in the array. The jsfiddle has the full html section, any help would be GREATLY appreciated.
Please bear in mind that I am not very good with terminology, so be as specific as possible. Especially regarding jQuery, our teacher didn't go over it much so it's a freaking mystery to me.
Also, I do plan on adding more information to the objects in the array, but until I get it working, I don't want to waste the time on something I might need to restructure.
http://jsfiddle.net/GamerGorman20/nw8Ln6ha/11/
var favWebComics = [
Goblins = {1: "www.goblinscomic.org"},
GirlGenious = {1: "www.girlgeniousonline.com"},
GrrlPower = {1: "www.grrlpowercomic.com"}
];
var myFunction = function() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
document.getElementById("web").innerHTML = favWebComics.x;
};
Again, the JSFiddle link has the full html, there are some unused items currently, but I do plan on adding more of them soon.
My next plan is to incorporate images into the objects, so a picture loads for each selection option. How would I manage that?
[ ] is used for arrays, which are indexed with numbers. If you want named properties, you should use an object, which uses { } for its literals:
var favWebComics = {
Goblins: "www.goblinscomic.org",
GirlGenious: "www.girlgeniousonline.com",
GrrlPower: "www.grrlpowercomic.com"
};
= is for assigning to variables, not specifying property names in an object.
Then you need to understand the difference between . and [] notation for accessing objects. .x means to look for a property literally named x, [x] means to use the value of x as the property name. See Dynamically access object property using variable.
So it should be:
document.getElementById("web").innerHTML = favWebComics[x];
your array is not structured correctly and an object would be better suited:
var favWebComics = {
Goblins : "www.goblinscomic.org",
GirlGenious : "www.girlgeniousonline.com",
GrrlPower : "www.grrlpowercomic.com"
};
then you should be able to access the properties as you intend
favWebComics.Goblins
favWebComics.GirlGenious
favWebComics.GrrlPower
Technically you were treating the array like a dictionary. if you're going to do that but still wanna add more information later you'll need to use brackets {} on the code.
var favWebComics = {
Goblins: ["www.goblinscomic.org"],
GirlGenious: ["www.girlgeniousonline.com"],
GrrlPower: ["www.grrlpowercomic.com"]
};
Also for javascript, as long as your searching key value stores, use braces [] for the call. Here's the working code below.
document.getElementById("web").innerHTML = favWebComics[x];
I have your solution, that displays:
the selected choice
the url
the images
Please check the fiddle.
http://jsfiddle.net/nw8Ln6ha/13/
Your object would be:
var favWebComics = {
Goblins : {url:"www.goblinscomic.org", img:"img1"},
GirlGenious : {url:"www.girlgeniousonline.com", img:"img2"},
GrrlPower : {url:"www.grrlpowercomic.com", img:"img3"}
};
Your display code:
document.getElementById("demo").innerHTML = "You selected: "+x+" "+ eval("favWebComics[\""+x+"\"].url")+" "+ eval("favWebComics[\""+x+"\"].img");

How to parse a JSON array

new here and hit a roadblock, been searching but can't find the answer with my skill set. Task is pretty simple, I want to parse this http://data.sparkfun.com/output/AJ2p4r8Owvt1MyV8q9MV.json which is from a weather station. I have used the W3C tutorial but just can't seem to parse this file, but http://json.parser.online.fr has no problem. All the looping parse examples just give me alert after alert.
All I want is the ability to select temp[0] (out of god knows how many) for example via javascript and have it display on a website. I'm really lost, tried searching and if I've missed the goldmine then my bad. Thanks!
Example code
var text = '[{"humidity":"42.8000","stationtime":"2014-07-06 19:43:52","temp":"23.3000","timestamp":"2014-07-06T09:44:07.918Z"},{"humidity":"‌​43.0000","stationtime":"2014-07-06 19:42:57","temp":"23.2000","timestamp":"2014-07-06T09:42:22.003Z"},{"humidity":"‌​43.2000","stationtime":"2014-07-06 19:42:36","temp":"23.3000","timestamp":"2014-07-06T09:42:51.737Z"}]';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.temp[0];
First, you need to parse the incoming string as below:
temp_arr = JSON.parse(json_string);
Just loop over the temp_arr array, and in each iteration of loop you'll have one object (tobj). For example, like this:
{"humidity":"40.9000","stationtime":"2014-07-06 21:21:03","temp":"22.6000","timestamp":"2014-07-06T11:20:27.231Z"}
All you have to do is, access it like tobj.temp and use it to display on page.
I have written a jquery implementation at: http://jsfiddle.net/DNH5n/2/
Jquery makes working with JSONP much easier heres an example (http://jsfiddle.net/icodeforlove/9mBsr/)
$.getJSON('http://data.sparkfun.com/output/AJ2p4r8Owvt1MyV8q9MV.json?callback=?', function (data) {
data.forEach(function (item) {
$('body').append(JSON.stringify(item));
});
})
update again
heres another example using your code (http://jsfiddle.net/icodeforlove/9mBsr/2/)
var text = '[{"humidity":"42.8000","stationtime":"2014-07-06 19:43:52","temp":"23.3000","timestamp":"2014-07-06T09:44:07.918Z"},{"humidity":"‌43.0000","stationtime":"2014-07-06 19:42:57","temp":"23.2000","timestamp":"2014-07-06T09:42:22.003Z"},{"humidity":"‌43.2000","stationtime":"2014-07-06 19:42:36","temp":"23.3000","timestamp":"2014-07-06T09:42:51.737Z"}]';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj[0].temp;

How to access first or specific object from json data

I have a json file with below mentioned format
mydata.json
{
"nodes":{
"Aidan":{"color":"green", "shape":"dot", "alpha":1, "id" : "aidan"},
"Sofia":{"color":"green", "shape":"dot", "alpha":1},
"Liam":{"color":"GoldenRod", "shape":"dot", "alpha":1}
},
"edges":{
"Quinn":{
"Liam":{"length":2.5,"weight":2},
"Audrey":{"length":2.5,"weight":2},
"Noah":{"length":2.5,"weight":2},
"Claire":{"length":2.5,"weight":2}
},
"Liam":{
"Sofia":{"length":2.5,"weight":2},
"Ethan":{"length":2.5,"weight":2},
"Amelia":{"length":2.5,"weight":2}
}
}
}
I will be reading above file data using jquery as mentioned below
var data = $.getJSON("data/mydata.json",function(data){
var nodes = data.nodes;
var edges = data.edges;
//i want to access first element or between element.
//like var edge = edges.get(0) or nodes.get("aidan")
})
I want to access first element or between element with the index or by name property of object. like var edge = edges.get(0) or nodes.get("aidan").
Thanks
There are several ways of doing it
Object.keys(nodes)[0]; //retrieve the first key
edges['Quinn'];
edges.Quinn
A little warning on the first one, Object in JS are unordered so it may break, thus browser tends to keep the insertion order.
hope it helped
Try this code
nodes['aidan']
edges['Quinn']
Either the before mentioned code
nodes['aidan']
or
nodes.aidan
should work equally fine.
Prepared a fiddle for you. You can check there.

Array constructor "new Array()" can be overwritten and replaced with malicious code, how?

We can create an array in a couple of ways:
var myArray = new Array();
Or:
var myArray = [];
The second way is safer to use than the new Array() syntax, because the Array constructor can be overwritten and potentially replaced with malicious code.
I have seen above lines in many JavaScript books but I don't understand how an Array constructor can be overwritten and replaced with malicious code? I'm looking for an example of how someone can do it, so that I can understand the reality of the issue.
Somewhere in the code above:
Array.prototype.forEach = function (e){
console.log("something wrong there");
return(e);
};
Somewhere in the code below:
var i = [1,2,3,4,5];
i.forEach(function(e){
console.log(e);
});
Output:
>"something wrong there"
As you can see, there is no difference how to initialize array variable. var i = []; just shorter notation.
If you write on your JS console :
[1,2,3]
(just like that) - you can do nothing with it.
Well that's not accurate with old browsers.
You could overload the array ctor by :
Array = new function (){... }
and so , when you got your friend list via Json ( not jsonp) : -
someone could use an XSS/XSF attack and steal your friends list.
The thing ere is the fact that : if you write [1,2,3] - there is actually a ctor working here.
So if you got to a website which does array response - he could still your list.

Categories

Resources