Using jQuery.data to store a list of items - javascript

I'm working on a page where I need to associate a list of objects with a row of a table, and I'm using jQuery.
jQuery.data seems to just associate a piece of data with a key, whereas I need more like
id=4,setting=2
id=3,setting=1
...
I don't know how long the list could be, and it could be empty.
Is there a sensible way of doing this?

You can store anything as jQuery data, so you could do this:
var myData = [ { id: 4, setting: 2 }, [ id:3, setting:1 ] };
$("#myitem").data("mydata", myData);
If you want to select something by id, you could do this:
var myData = {};
myData[4] = 2;
myData[3] = 1;
$("#myitem").data("mydata", myData);
Then you can access your settings like this:
var value = $("#myitem").data("mydata")[3]; // returns 1

I haven't got a great amount of time to try it now, but instead of storing a simple string against the key, why not store an object against it?
To paraphrase the jquery docs...
$("div").data("blah", {id: 4,setting: 2});
var myBlah = $("div").data("blah");
var id = myBlah["id"];
var setting = myBlah["setting"];
Let me know how you get on.

You can use arrays to store lists and JSON objects to store key-value pairs.
<div id="DIV1"></div>
<div id="DIV2"></div>
<div id="DIV3"></div>
<div id="DIV4"></div>
<table><tbody><tr id="TR1"><td><td/></tr></tbody></table>
<script type="text/javascript">
$(function() {
$("#TR1").data("blah", [{id: 4, setting: 2}, {id: 3, setting: 1}]);
$("#DIV1").text($("#TR1").data("blah")[0].id);
$("#DIV2").text($("#TR1").data("blah")[0].setting);
$("#DIV3").text($("#TR1").data("blah")[1].id);
$("#DIV4").text($("#TR1").data("blah")[1].setting);
});
</script>

Related

Populating form fields from JSON feed using forEach or for loop (JS)

I have form fields like these
<input id="first">
<input id="second">
<textarea id="third"></textarea>
...
and I need to dynamically populate them with data from a JSON feed.
Each field's id corresponds to each JSON's key, so I'm able to populate those fields this way:
first.value = feed.first;
second.value = feed.second;
third.value = feed.third;
...
But I would like to make it simpler.
This is what I've tried:
["first", "second", "third"].forEach(e => {e.value = feed[e]});
Sadly, it doesn't work. In console I can see JSON feed's values (feed[e]), but form fields are blank.
What am I doing wrong?
Any suggestions would be much appreciated.
You can try using document.getElementById to get specific DOM element
and then assign the value you want.
const feed = {
'first': 'hello',
'second': 'word',
'third': '!'
};
['first', 'second', 'third'].forEach(e => {
document.getElementById(e).value = feed[e]
});
The link below is a full demonstration.
https://jsfiddle.net/2x0o8d4m/1/
Please use eval function.
["first", "second", "third"].forEach(e => {eval(e).value = feed[e]});

How do I programmatically build an object from my form data that includes arrays

I need to display some values on a jsp page, grab input from user and send it back to a controller that is using Jackson to bind it to my backing data object. Several rows that I display on the screen are backed by an array and are created with <c:forEach> and I'm generating a path like "blobs[0].id" and "blobs[0].text". When I try to put them into the json object to be sent back to the controller by an ajax call, they aren't being added to the object properly. The property name ends up having "[0]" in the name instead of representing the object at that array index.
<script>
var formData = {};
formData.blobs = [];
formData.blobs[0] = {};
formData.blobs[0].id = "English";
formData.blobs[0].text = "Hello";
formData["blobs[1].id"] = "German";
formData["blobs[1].text"] = "Guten Tag";
console.log(formData);
</script>
ends up looking like {blobs: [0 : {id: "English", text: "Hello"}], blobs[1].id: "German", blobs[1].text: "Guten Tag"} instead of
{blobs: [0 : {id: "English", text: "Hello"}, 1 : {id: "German", text: "Guten Tag"}]}
I am trying to assemble the model thusly:
<script>
function createModel() {
var form = $("#theForm");
var formData = {};
$.each(form, function(i, v){
var input = $(v);
if (input.attr("name")) {
formData[input.attr("name")] = input.val();
}
});
}
</script>
Accessing obj["attr"] is an option to access an object's attribute, so obj["attr[1][22]"] will access an attribute called "attr[1][22]", while accessing obj["attr"][1][22] will access the second element of obj.attr, and the second element's 22th element as well..
The solution will be to access formData["blobs"][0].id or even formData["blobs"][0]["id"]
you can format the string to your needs
$('#yourform').serializeArray() returns an array:
[
{"name":"foo","value":"1"},
{"name":"bar","value":"xxx"},
{"name":"this","value":"hi"}
]
$('#yourform').serialize() returns a string:
"foo=1&bar=xxx&this=hi"
so, in your case
var formData = {};
formData.blobs = [];
$('#yourform').serializeArray().forEach(function(blob){
formData.blobs.push({
id: blob.name,
text: blob.value
});
})

Naming a JSON array using Jquery

I have an array of JSON:
[{"AvatarURL":"https://avatars1.githubusercontent.com/u/7849225?v=4","Name":"simplenlg","Score":22.82041,"Updatedat":"2018-07-21T10:58:33Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/8931462?v=4","Name":"aws-microservices-deploy-options","Score":20.521696,"Updatedat":"2018-07-20T12:22:07Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/4046529?v=4","Name":"useful-jenkins-groovy-init-scripts","Score":21.447626,"Updatedat":"2018-07-18T19:52:02Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/6755615?v=4","Name":"dnsjava","Score":34.74705,"Updatedat":"2018-06-28T15:16:45Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/504773?v=4","Name":"luke","Score":19.239859,"Updatedat":"2018-06-28T07:27:26Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/536912?v=4","Name":"Wicket-tutorial-examples","Score":37.265644,"Updatedat":"2018-07-14T04:28:50Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/33330803?v=4","Name":"nexus-repository-apt","Score":44.401646,"Updatedat":"2018-07-06T18:28:13Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1321963?v=4","Name":"marc4j","Score":28.282797,"Updatedat":"2018-07-07T15:58:57Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/5622390?v=4","Name":"jamonapi","Score":24.564436,"Updatedat":"2018-07-16T07:44:35Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1123352?v=4","Name":"osgi.enroute","Score":7.6444883,"Updatedat":"2018-07-17T08:26:51Z"}]
I want it to be:
{
gitdList: [
{"AvatarURL":"https://avatars1.githubusercontent.com/u/7849225? v=4","Name":"simplenlg","Score":22.82041,"Updatedat":"2018-07-21T10:58:33Z"},
{"AvatarURL":"https://avatars2.githubusercontent.com/u/1123352?v=4","Name":"osgi.enroute","Score":7.6444883,"Updatedat":"2018-07-17T08:26:51Z"}
]
}
I searched and am finding solutions regarding php only , to use json.encode.
How do I do it using JQUERY?
Have you try like this way? just create an empty object like this object = {} and assign your existing value i.e avatar_urls to it with your desired key i.e gitdList. Hope this will work for you.
var avatar_urls = [{"AvatarURL":"https://avatars1.githubusercontent.com/u/7849225?v=4","Name":"simplenlg","Score":22.82041,"Updatedat":"2018-07-21T10:58:33Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/8931462?v=4","Name":"aws-microservices-deploy-options","Score":20.521696,"Updatedat":"2018-07-20T12:22:07Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/4046529?v=4","Name":"useful-jenkins-groovy-init-scripts","Score":21.447626,"Updatedat":"2018-07-18T19:52:02Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/6755615?v=4","Name":"dnsjava","Score":34.74705,"Updatedat":"2018-06-28T15:16:45Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/504773?v=4","Name":"luke","Score":19.239859,"Updatedat":"2018-06-28T07:27:26Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/536912?v=4","Name":"Wicket-tutorial-examples","Score":37.265644,"Updatedat":"2018-07-14T04:28:50Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/33330803?v=4","Name":"nexus-repository-apt","Score":44.401646,"Updatedat":"2018-07-06T18:28:13Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1321963?v=4","Name":"marc4j","Score":28.282797,"Updatedat":"2018-07-07T15:58:57Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/5622390?v=4","Name":"jamonapi","Score":24.564436,"Updatedat":"2018-07-16T07:44:35Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1123352?v=4","Name":"osgi.enroute","Score":7.6444883,"Updatedat":"2018-07-17T08:26:51Z"}]
var object = {};
object.gitdList = avatar_urls;
console.log(object);
Edit: pretty neat and better way to do it.
var object = { gitdList: avatar_urls};
console.log(object);
maybe like this:
var data=[{"AvatarURL":"https://avatars1.githubusercontent.com/u/7849225?v=4","Name":"simplenlg","Score":22.82041,"Updatedat":"2018-07-21T10:58:33Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/8931462?v=4","Name":"aws-microservices-deploy-options","Score":20.521696,"Updatedat":"2018-07-20T12:22:07Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/4046529?v=4","Name":"useful-jenkins-groovy-init-scripts","Score":21.447626,"Updatedat":"2018-07-18T19:52:02Z"},{"AvatarURL":"https://avatars1.githubusercontent.com/u/6755615?v=4","Name":"dnsjava","Score":34.74705,"Updatedat":"2018-06-28T15:16:45Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/504773?v=4","Name":"luke","Score":19.239859,"Updatedat":"2018-06-28T07:27:26Z"},{"AvatarURL":"https://avatars3.githubusercontent.com/u/536912?v=4","Name":"Wicket-tutorial-examples","Score":37.265644,"Updatedat":"2018-07-14T04:28:50Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/33330803?v=4","Name":"nexus-repository-apt","Score":44.401646,"Updatedat":"2018-07-06T18:28:13Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1321963?v=4","Name":"marc4j","Score":28.282797,"Updatedat":"2018-07-07T15:58:57Z"},{"AvatarURL":"https://avatars0.githubusercontent.com/u/5622390?v=4","Name":"jamonapi","Score":24.564436,"Updatedat":"2018-07-16T07:44:35Z"},{"AvatarURL":"https://avatars2.githubusercontent.com/u/1123352?v=4","Name":"osgi.enroute","Score":7.6444883,"Updatedat":"2018-07-17T08:26:51Z"}];
var new_data={ 'gitdList': data };
console.log(new_data);

Add [DataObject] to exsisting array with var key

Using Cordova, I am trying to get an Object to add to an array. I have this working on node JS using :
theData = {[varkey]:DataObject};
But I can't get this to work the same way within my javascript that cordova runs.
I need to do the following:
var TownName = 'Auckland', var townData = (JSON Data);
theArray = new Array();
theArray[TownName] = townData;
I need to be able to call it back as:
theArray['Auckland']
Which will return (JSON Data)
But it doesn't want to store the data with the key inside the array.
I have also tried:
theArray.TownName = townData;
theArray = [{TownName:townData}];
theArray = {[TownName]:townData}];
Nothing wants to store the data.
Any suggestions?
::EDIT::
data.theData =
"Auckland"[
{
"username":"pndemoname1",
"number":"373456",
"www":"http://373456.pndemoname1",
"icon":"/imgs/pndemoname1.png"
},
{
"username":"pndemoname2",
"number":"373458",
"www":"http://373458.pndemoname2",
"icon":"/imgs/pndemoname2.png"
}
data.town = "Auckland";
townData = new Array();
alert(JSON.stringify(data.theData))//Alerts theData
townData[data.town] = data.theData
alert(townData[townName]) //Alerts undefined
::EDIT2::
Re-defining the array within the function that deals with all of the data, seems to make it work.
As per my answer, the issue was that I assumed javascript vars are global.
Use objects or an array of objects.
A data structure like this:
{
town1: town1Data,
town2: town2Data,
}
Or more common:
[
{
name: "Town 1",
data: {...}
},
{
name: "Town 2",
data: {...}
},
]
For reference:
http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/
I got what you're trying to do, to add property names dynamically to your object is first, by making sure you are using an OBJECT instead of an array, so when you want to store something you will do the following:
var _obj = {}, _something = 'xyz';
_obj[ _something ] = { ... }; // json structure
The problem you're facing is that you want to assign a string value as a key inside your array, which will not work.
However, you can still use the array you defined and do the following:
var _array = new array();
_array.push( { .... } ); // insert json structure
Remember! By using the array you will have to loop through all values every time you want to access your key, just as the best practice to avoid getting into errors.
Good luck.
The issue was that I didn't define the array within the function of where I was trying to add the information to.
I assumed the var was global (Too much PHP)

How could I iterate the values in ArrayList in java from java script?

I have stored a bulk of objects in an ArrayList and I have set that in the request. Now I want to retrive the values in the Arraylist from my java script. Please help me with the solution
You can use JSON to facilitate the exchange of information between Java and Javascript. Libraries are available on both ends.
To put the elements of a List into an array, you can use Collection.toArray.
You need to serialize them as javascript first.
There are 2 ways to do it:
1) Universal way - https://stackoverflow.com/questions/338586/a-better-java-json-library
You just put in your jsp something like this:
<script...>
var myArray = <% JSON.Serialize(myArray) %>;
</script>
2) Fast and dirty:
<script...>
var myArray = [
<c:forEach items="${myArray}" var="item">
{
name = "<c:out value="${item.name}">",
text = "<c:out value="${item.text}">"
},
</c:forEach>
];
</script>
Both will result in Javascript like this, and can be used in JS:
var myArray = [
{
name = "Mike",
text = "Hello world"
},
{
name = "Max",
text = "Hi!"
}
];

Categories

Resources