I'm trying to use two arrays to populate a couple of each statements instead of writing it out 20 times for every attribute.
Here's what I was thinking. The idea here is to get the data (stored in mainData). I need a number of objects from this data, so I put those in an array ($dataPoints). I'm taking all of this data an appending it to a table. I'm adding the data to specific rows with specific ids (stored in $tableIds).
So, the basic idea...for every item in $dataPoints, look up that part of the data and append it to the table in the place indicated by the ids in the same position in the array. Like so...
var $dataPoints = ['name','description','subtitle'];
var $tableIds = ['mNames','mDescription','mSubtitle'];
$.each($dataPoints, function(index, val) {
$.each(mainData.val[index].source_values, function(index, val) {
$("#matrix_datatable").find('#'+$tableIds[index])
.append($('<td class="tableCells">')
.append(val.value + '</td>')
)
});
});
However, this line:
$.each(mainData.val[index].source_values, function(index, val) {
is throwing an error:
Uncaught TypeError: Cannot read property '0' of undefined
What am I missing here? Is there a simpler way to do this?
EDIT: Note that this works perfectly.
$.each(mainData.subtitle.source_values, function(index, val) {
$("#matrix_datatable").find('#mSubtitle')
.append($('<td class="tableCells">')
.append(val.value + '</td>')
)
});
However, I don't want to write this out for the 20 different objects within mainData.
It looks like you probably meant:
mainData[val][index].source_values
Writing mainData.val literally looks for a key val in mainData.
Related
I receive a json from an API that I need to parse and modify one property value. Thing is, the nesting structure of the json data I receive are inconsistent and I have no control over it.
This will prohibit me to specify to look under a certain depth like parsedJson.children[0].property since the property I'm looking for could be found on a different nesting level like parsedJson.children[0].children[0].property on the next iteration.
I currently do it like this, and it works
var parsedJson = JSON.parse('{"a":[{"a1":[{"p":0},{"np":1}]}],"b":[{"p":0},{"np":1}],"c":[{"c1":[{"c2":[{"p":0}]},{"np":1}]}]}')
console.log("before modify")
console.log(parsedJson)
modifyProperty(parsedJson,"p",1);
function modifyProperty(obj,prop,val){
for (var key in obj){
if (key == prop){
obj[key] = val;
}
modifyProperty(obj[key],prop,val);
}
}
console.log("after modify")
console.log(parsedJson)
but I'm afraid later on, if I received a json from API that contains a lot more data and far deeper nesting levels that it may affect performance since this would need to recursively check all children nodes one by one.
Is there a better / faster way to this?
You can pass a second parameter to JSON.parse that recursively transforms all desired property values:
var parsedJson = JSON.parse(
'{"a":[{"a1":[{"p":0},{"np":1}]}],"b":[{"p":0},{"np":1}],"c":[{"c1":[{"c2":[{"p":0}]},{"np":1}]}]}',
(key, val) => key === 'p' ? 1 : val
);
console.log(parsedJson);
I'm trying to output values from an array that has one key and multiple values in a JSON file. I've managed to output the values using $.each(), but what happens is that the value is returned as an array, because it is an array! I want to output each value individually so that the output is not an array:
<img src="one-value-output" />
<img src="two-value-output" />
etc...
JSON
var dataJson = "http://www.reneinla.com/kris/scripts/print.json";
The JSON file looks like this:
{
"printImages":[
"http://reneinla.com/kris/images/print/2008-06_KZO_TEN_01.jpg",
"...",
"http://reneinla.com/kris/images/print/2008-06_KZO_TEN_03.jpg"
]
}
JAVASCRIPT
var dataJson = "http://www.reneinla.com/kris/scripts/print.json";
//var dataArr = $.parseJSON(dataJson);
$.getJSON(dataJson, function (data) {
$.each(data, function (k, v) {
console.log( v );
});
});
I'd like to be able to output each value and append it to an src attribute, but wanted to see the console.log output first.
First Question
How do you print out, console.log, all the values from the json file?
Second Question
Is this the right approach to what i'm trying to achieve? I thought I'd use a JSON file because I have 88 values that need to be appended into the DOM. I could make the JSON file into an object, in my js file, but wanted to keep it more organized and efficient. This is still fairly new, so any insight here would be appreciated. Thanks and regards!
EDIT
I was able to get my desired result using this code:
var dataJson = "http://www.reneinla.com/kris/scripts/print.json";
//var dataArr = $.parseJSON(dataJson);
$.getJSON(dataJson, function (data) {
$.each(data, function (k, v) {
var i = 0;
for (i; i < v.length; i++){
console.log( v[i] );
}
});
});
Hooray!
Looking at your JSON, what you have is an object with 1 property, which is an array of strings.
Using developer tools, you should set a breakpoint inside the $.getJSON success callback function to inspect the value of data. You'll see that data is not an array, but that you should actually be going after data.printImages. Otherwise, your code looks OK to me.
Re: Your approach. It seems like a good idea to me. Some day you might change the static .json file out for a server processed file, and you probably wouldn't have to change the client side at all to do that, other than point at a different URL.
I have some code like this:
var optgroup = $('#myselect').val();
var optarray = optgroup.split(',');
alert(optarray.join("\n"));
The first line returns something along the lines of "option1,option2,option3" if all three options are selected. I want it to return a separate result for each option. I have tried the above code but I keep getting the error:
Uncaught TypeError: undefined is not a function
I'm not sure what the error is about, any help would be appreciated. As a side note, when these values are separated, I'm going to cycle through the array and store each option on a different row of a table in SQLite.
If you want to have the list of possible selections you can use the following code:
var list = '';
$('#myselect option').each(function(){
list = list + $(this).val() + '\n';
});
console.log(list);
I have a collection of objects, which is retrieved in JavaScript/JQuery through EL (at least that is what I think). I name the variable "countries". Upon calling alert(countries), my output is as expected. I have four elements, as it should be.
I thought it would be the easiest thing in the world, but for an unknown reason, it just doesn't work So... help?
var countries = "${requestScope.countries}";
alert(countries) gives the following output:
[beans.CountryBean#(id#), beans.CountryBean#(id#),
beans.CountryBean#(id#), beans.CountryBean#(id#)]
#AaronDigulla suggested the following syntax:
$.each(countries, function(index, value) { ... });
But this, almost identical code, gives no output.
$.each(countries, function(index, value) { alert(index + "here");});
Am I just wrong in assuming it would produce 4 alerts?
Use $.each(countries, function(index, value) { ... });
$.each() can iterate over all kinds of things (arrays, objects and JQuery selectors).
Next, you need to convert the beans to JavaScript. The browser can't understand beans.CountryBean#(id#). Use a JSON framework like Gson to create a JSON string:
var countries = ${new Gson().toJson(requestScope.countries)};
note that you must not quote the string anymore; Gson will do this for you. But I fear this expression is out of the scope of what EL can do. In that case, you need to do the conversion elsewhere and put it into the EL context.
I am trying to add values into an array but for some reason it is not working. I am new to JavaScript.
Here is my code:
eventsArray = new Array();
$.each(xmlJsonObj.feed.entry, function(index, value){
eventsArray[index] = new Array('title' = value.title, 'date' = value.date[1]);
});
So basically I am pulling out some values from the json object and want to save them as key-value pairs in an array (multidimensional as each event has several values).
This array will later be sorted by date.
I am currently getting the following error:
ReferenceError: Left side of assignment is not a reference.
I am new to JavaScript and don't really understand whats wrong. Tried to look at some examples but still can't see a good example of creating two dimensional arrays with JavaScript (or objects, as everything in JS is an object) in a loop like this.
I would be very thankfull for any help or tips.
The cause of the error message is this:
'title' = value.title
That would mean that you are trying to assign a value to a literal string. The rest of the code (except from the other one just like it) is actually valid syntax, even if that is not what you are trying to do, so that's why you get the error message on that part of the code.
To have a collection of key-value pairs you would use an object instead of an array, and you can create it like this:
eventsArray[index] = { title: value.title, date: value.date[1] };
May be simplest one,
var eventsArray = new Array();
$.each(xmlJsonObj.feed.entry, function (index, value) {
eventsArray[index] = { 'title': value.title, 'date': value.date[1] };
});
It works if you change your code to:
var eventsArray = new Array();
$.each(xmlJsonObj.feed.entry, function(index, value){
eventsArray.push({ title : value.title, date: value.date[1] });
});
You should use objects for this:
eventsArray[index] = {};
eventsArray[index].title = value.title;
eventsArray[index].date = value.date[1];
The problem you have is that you try to assign value.title value to String. Arrays in JS didn't work in that way. Also Arrays didn't support String keys, this is why you may need Object.
If your date property is TIMESTAMP for example you can sort it like:
eventsArray.sort( function( a, b ) {
return a.date - b.date;
});