Creating JSON - part loop, part plain string - javascript

I have the below code, which loops through the DOM looking for elements that have an id starting with "sale-", with an attribute "data-id", capturing the value, then stripping the opening and closing square brackets - pushing it all into a JSON object:
els = $("div[id^='sale-']");
Array.prototype.forEach.call(els, function(el) {
var id = el.attributes[2].value.replace(/\[|\]/gi, "");
var jsonObject = {"id" :+id};
var myJSON = JSON.stringify(jsonObject);
console.log(myJSON+",")
});
This works and the output is:
Now the problem comes when I want to apply some static JSON code before and after the loop.
I would like something like the below:
// static
dataLayer.push({
'ecommerce': {
'impressions': [
// loop portion
{"id":50450},
{"id":49877},
{"id":49848},
{"id":49912},
{"id":49860},
{"id":49825},
{"id":48291},
{"id":49667},
// static
]
}
});

Firstly you can make the array creation much more simple by calling map() on the jQuery object. From there you can simply add the resulting array to an object with the required structure. Try this:
var idArr = $("div[id^='sale-']").map(function() {
var id = this.attributes[2].value.replace(/\[|\]/gi, "");
return { id: +id };
}).get();
dataLayer.push({
ecommerce: {
impressions: idArr
}
});
Also note that this.attributes[2].value can be improved, but you haven't stated which attribute you're expecting that to target.

Related

Need to display full array as a string in an innerHTML element

Ok this must have a simple solution but I'm breaking my head over this one...
I have a js code which picks up ID numbers from my HTML by class. It stores all in an array. I checked that the array is not undefined and is not empty. Sofar so good.
Now I need to get this array of ID's to display into an HTML element. The full array should just come out as a comma separated string.
The piece of code which is relevant:
function makelink(){
var idArray = $(".result");
document.getElementById("link").innerHTML = idArray;
}
//The result in HTML = [object Object]
When I do the following it works exactly as I want (except that I can't hardcode the array into the code like this of course)
function makelink(){
var idArray = ["123", "124", "125", "126"];
document.getElementById("link").innerHTML = idArray;
}
//The result in HTML = [123,124,125,126]
I read at least 4 other similar questions on Stackoverflow such as What does [object Object] mean? and Convert javascript array to string and based on that I tried:
document.getElementById("link").innerHTML = idArray.join();
and also:
var idArray = $(".result");
idArray.toString();
but I could not figure out how to make it work for my code. I don't need to alert or console.log. I need my result to be output in the HTML. Please help.
You can try this:
function makelink(){
var idArray = [];
$(".result").each(
function(){
idArray.push($(this).text())
}
);
document.getElementById("link").innerHTML = idArray.join(', ');
}
You are not displaying the array, but the jQuery object of the DOM element. You might need the map function. But this function is not enough by itself, you will still need to get the value of the result object, or the html, but that part is the easiest.
function makelink(){
var idArray = $(".result").map(function(item) {
return item.val();
}).get();
document.getElementById("link").innerHTML = idArray;
}
Do this ::
function makelink() {
var idArray = ["123", "124", "125", "126"];
document.getElementById("link").innerHTML = JSON.stringify(idArray);
}

Can't get div attributes with jquery's attr()

The following code:
<div id='idiv' name='ndiv'>
<script>
var attrs = $('#idiv').attr({})
var astr = JSON.stringify(attrs)
console.log (astr)
</script>
produces in the console:
{"0":{},"length":1,"context":{"location":{}},"selector":"#idiv"}
Why isn't the result:
{"id":"idiv","name":"ndiv"}
How do I get the latter?
Try this:
<div id='idiv' name='ndiv'>
<script>
var attrMap = $('#idiv')[0].attributes;
var attrs = {};
$.each(attrMap, function(i,e) { attrs[e.nodeName] = e.value; });
console.log(attrs); // Object {id: "idiv", name: "ndiv"}
console.log(JSON.stringify(attrs)) // {"id":"idiv","name":"ndiv"}
</script>
Fiddle: http://jsfiddle.net/xbuhbqux/
If you want to create an object of all the attributes of an element, refer to this SO answer
to produce the object you have shown:
var idiv = $('#idiv');
var attrs = JSON.stringify({
"id": idiv.attr("id"),
"name": idiv.attr("name")
});
console.log(attrs);
jQuery operators are often chainable and usually return arrays of elements, rather than individual elements.
What you are doings is actually returning a list of matching elements, and asking for attributes for all items in that list, which is also returning a list elements. The JSON.stringify reflects that.

How to create Dictionary [Key : value] in jQuery

I have a input elements in html with two important attributes: id, and parentElementId.
I want to create a map/dictionary that looks like this: "id : parentElementId".
var parent = $(".people-autocomplete").map( function(){ return $(this).attr('id')+':'+$(this).attr('parent'); }).get() ;
for know I'm putting the values into a string, which I parse later on in the code. I presume there is a more elegant solution than this.
Use an object:
var obj = {};
$(".people-autocomplete").each(function() {
obj[$(this).attr('id')] = $(this).attr('parent');
});
You can then access the parent of a specific id:
var parent = obj.idName;
or through a string:
var idStr = 'idName';
var parent = obj[idStr];
And you can loop through:
for (idStr in obj) {
var parent = obj[idStr];
}
You can use JSON object for this purpose, You are confusing the usage of .map() in Jquery with map of other languages.
You can create a Json object like,
var xObj = {};
xObj.id = 'parentElemtnId';
alert(JSON.stringify(xObj)); // { id : 'parentElementId' }

Jquery post a Array

I am having a Array which is generated by my Javascript in run time.
once that array is full with all the values I want to send it using POST to the server.
How can I do that ...
Pseudo code:
for(i=0;i<result.data.length;i++)
{
result.data[i].id
}
$.post("receiver.php", { xxxxx }, function(data){ console.log(data);});
How can I get that xxxx updated in the post
I checked the documentation in jquery but they are expecting to give all the values in POST.I do not want to do that.
Also, I want to send post only once so that traffic will be less.
EDIT
You can use join() to get all your array values converted to a string, using some char to separate it.
EDIT 2: As Kumar said he was using 2 arrays
var idsArray;
var namesArray;
for(i=0;i<result.data.length;i++)
{
idsArray[] = result.data[i].id;
namesArray[] = result.data[i].name;
}
var ids = idsArray.join(",");
var names = namesArray.join(",");
$.post("receiver.php", { ids:ids, names:names }, function(data){ console.log(data);});
similar to iBlue's comment, You can just send an object with post; you don't have to define the object in the post function, { } are simply the delimiters to define objects, which are similar to PHP associative arrays:
$.post('reciever.php', myData, function(data){ /*callback*/ });
The only thing is that you setup myData as an object like follows:
myData = {
0: 'info',
1: 'info'
}
//or even something like this
myData = {
someProp: 'info',
someProp2: {
anotherProp: 'moreInfo'
}
}
you can also use non-numerical indexes with objects, and easily add properties:
myData[2] = 'info';
or you can loop through it, just in a slightly different way:
for(i in myData){
myData[i]; //Do something with myArr[i]
}
the for in loop will also loop through non-numerical properties. And you can still get the length of myData by
myData.length;
EDIT:
Instead of sending a string:
IDs = {}
Names = {}
for(var i = 0; i < result.data.length; i++){
IDs[i] = result.data[i].id;
Names[i] = result.data[i].name;
}
$.post('reciever.php', {IDs: IDs, Names: Names}, function(data){});
In the PHP file you would access them like so
$_POST['IDs'][0] = "some id";
$_POST['Names'][0] = "some name";
EDIT:
Actaully I think the indexes are sent as strings, so might have to do
$_POST['IDs']['0']
Not sure, but it seems like you want to do this:
var sendObj = {};
for (var i=0; i<result.data.length; i++) {
var id = result.data[i].id,
name = result.data[i].name; // or some similiar computation
sendObj[name] = id;
}
$.post("receiver.php", sendObj, function(data){ console.log(data);});
This will send the result.data as name=id-value-pairs.

Get JSON object by attribute

Say I have this JSON object:
var images = {"success":"true", "images":[
{"id":"1234","url":"asdf","tags":["cookie","chocolate"]},
{"id":"5678","url":"qwer","tags":["pie","pumpkin"]}
]};
What would be the most efficient way to get the url of the image with an id of 5678? Can use jQuery.
Because it's an array and you're looking for an embedded property, not just a simple array value, there isn't really a super-efficient way to find it. There's the brute force mechanism of just walking through the array and compare each id to what you're looking for.
If you're going to be looking up these kinds of things in this same data structure multiple times and you want to speed it up, then you can convert the existing data structure into a different data structure that's more efficient for accessing by ID like this:
var imagesById = {
"1234": {"url":"asdf","tags":["cookie","chocolate"]},
"5678": {"url":"qwer","tags":["pie","pumpkin"]}
}
Then, finding an object by id is as simple as this:
imagesById["1234"]
url = $.grep(images.images, function(item) { return item.id === '5678' })[0].url;
Unless the IDs are sorted, you can't do better than plain old iteration:
var images = {"success":"true", "images":[
{"id":"1234","url":"asdf","tags":["cookie","chocolate"]},
{"id":"5678","url":"qwer","tags":["pie","pumpkin"]}
]};
var inner = images.images,
targetId = '5678',
found = null;
for (var i=0; i<inner.length; i++) {
if (inner[i][id] === targetId) {
found = inner[i];
// do stuff...
break;
}
}
You'd have to loop through the array:
$.each(images.images,function(i,img) {
if(img.url == "5678") {
//do whatever you want with this url
}
}

Categories

Resources