How do I store JSON objects in indexedDB? - javascript

my return json file looks like this:
var data = [{"col1":"value1","col2":"value1","col3":"value1"},{"col1":"value2","col2":"value2","col3":"value2"},{"col1":"value3","col2":"value3","col3":"value3"}];
without JSON.stringify data looks like this:
[object Object],[object Object],[object Object]
but with it the result.length is not 5 but the total number of characters of the string and that way I cant do the loop
var result = JSON.stringify(data);
for(i=0; i<result.length; i++){
var transaction = db.transaction([STORE], IDBTransaction.READ_WRITE);
var put = transaction.objectStore(STORE).put(result);
};

var data = [{"col1":"value1","col2":"value1","col3":"value1"},{"col1":"value2","col2":"value2","col3":"value2"},{"col1":"value3","col2":"value3","col3":"value3"}];
If you are trying to store each OBJECT, then don't stringify it or anything, it is already in perfect form. Change your for() loop to loop through the data objects.
Kristof Degrave had a good point to put these outside of the actual for loop for performance reasons.
var transaction = db.transaction([STORE], IDBTransaction.READ_WRITE);
var objstore = transaction.objectStore(STORE);
for (i = 0; i < data.length; i++) {
objstore.put(data[i]);
}

For new visitors, suggesting a tad of modification:
IDBTransaction.READ_WRITE has been deprecated so use "readwrite" instead.
Resource: https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB
Reference:
Older experimental implementations use the deprecated constant
IDBTransaction.READ_WRITE instead of "readwrite".
Also, to reduce the loc (which I mostly prefer), use:
var objstore = db.transaction([STORE], "readwrite").objectStore(STORE);
for (i = 0; i < data.length; i++) {
objstore.put(data[i]);
}

Related

Angularjs can't get array length

I am trying to get the array length, when i console log
console.log($scope.community)
I do get a return, but when i try doing the method i found online , like Get the object length in angularjs is undefined
var array = Object.keys($scope.community);
var len = array.length;
console.log(len)
I am returned with 0 and no error
Array call :
var all = displayAll.callAll()
.then(function(response) {
$scope.all = response;
for (var i=0; i< $scope.all.length; i++) {
if ($scope.all[i].CATEGORY == 'Community')
{
$scope.community.push($scope.all[i]);
}
var len = $scope.community.length;
console.log(len);
should return the length of the community.
Plus this method can also be used in Native JS, even without using AngularJS.

concatenate an increment counter onto the end of an array selector within a json response loop

so I'm looping through a json response and I'm trying to use the counter (var i) to say data.newarray[i].time+i so with each loop the next array is chosen and the time also increases in number. So 1st loop will spit out data.newarray[0].time0 then data.newarray[1].time1 then data.newarray[2].time2 and so on. The bit that is currently failing is my concatenation time+i at the end. How do I format this to work?
var data = JSON.parse(xmlHTTP.responseText);
for(var i=0; i<data.newarray.length; i++)
{
alert(data.newarray[i].time+i);
}
You can access variable property names by using the quoted notation: obj['prop'] instead of obj.prop.
The solution is:
var data = JSON.parse(xmlHTTP.responseText);
for(var i=0; i<data.newarray.length; i++)
{
alert(data.newarray[i]['time'+i]);
}
Try something like this:
for(var i=0; i<data.newarray.length; i++) {
alert(data.newarray[i]['time'+i]);
}

Separate Array into two arrays

I wonder how I can separate an array that consists of "123.152323,152.123232" into "123.152323" and "152.123232".
I pick up the string from a rest, the string looks like this.
responseHandler({"items":[{"name":"xxx","location":["xx.xxxxx","xx.xxxxx"]...
function responseHandler(json) {
var markers = new Array();
for (var i = 0; i < json.items.length; i++) {
markers[i] = (json.items[i].location);
}
}
Can I split the location before putting it into an array? I know split() exists but if the string has more information than just location, such as name, city, etc.
Why reinvent the wheel ? It seems like you have a valid json object, Why not simply use JQuery.parseJSON
Modern browser contain native JSON methods (like JSON.parse, JSON.stringify). Use those, or use an external library like this one from google. It makes your life easier (no need for splitting or regex searches and the like):
function responseHandler(json) {
// use native (JSON.parse), json-sans-eval would be: jsonParse(json)
var myJson = JSON.parse(json)
,markers = []
,i = 0
,len = myJson.length;
for (; i < len; i = i+1) {
markers.push(myJson[i].location);
}
return markers;
}
Edit after comment: you are passing a js-object, so JSON-parsing is not necessary.
function responseHandler(json) {
var markers = []
,i = 0
,len = json.length;
for (; i < len; i = i+1) {
markers.push(json.items[i].location);
}
return markers;
}
//for example
var json = {"items":[
{"name":"xxx","location":["xx.xxxxx","xx.xxxxx"]},
{"name":"yyy","location":["yy.yyyyy","yy.yyyyy"]}
]
};
var locations = responseHandler(json);
//=> now locations[0][0] is 'xx.xxxxx', locations[1][0] 'yy.yyyyy'
(May be you should try finding some reading material on the web about javascript basics)

Convert a javascript string into a 2-dimensional array

I have this data coming from a REST method using jquery's getJSON method.
"[Date.UTC(2010,0,0,0,0,0,0), 157],[Date.UTC(2010,0,0,0,0,420,1), 157],[Date.UTC(2010,0,0,0,0,420,2), 282],[Date.UTC(2010,0,0,0,0,600,3), 282],[Date.UTC(2010,0,0,0,0,600,4), 125],[Date.UTC(2010,0,0,0,0,900,5), 125],[Date.UTC(2010,0,0,0,0,900,6), 282],[Date.UTC(2010,0,0,0,0,2100,7), 282],[Date.UTC(2010,0,0,0,0,2100,8), 125],[Date.UTC(2010,0,0,0,0,2400,9), 125],[Date.UTC(2010,0,0,0,0,2400,10), 295],[Date.UTC(2010,0,0,0,0,3600,11), 295],[Date.UTC(2010,0,0,0,0,3600,12), 125],[Date.UTC(2010,0,0,0,0,3900,13), 125],[Date.UTC(2010,0,0,0,0,3900,14), 288],[Date.UTC(2010,0,0,0,0,5100,15), 288],[Date.UTC(2010,0,0,0,0,5100,16), 125],[Date.UTC(2010,0,0,0,0,5400,17), 125]"
It comes back as a string. I need to parse it into a two dimensional array. Each item in the array should have a date and a value.
I also have full control over the REST method, so I could change the way the data returns. I'm interested in making this as fast as possible.
Here's what we are doing now which I think could be improved:
var jqxhr = $.getJSON(getDataURL, function(dataResult) {
var result = dataResult;
result =result.replace(/\]\,\[/g, ']:[');
result = result.replace(/\)\,/g, ');');
var tempArray = result.split(':');
var myarray = new Array();
myarray[0] = new Array(2); // Make the first element an array of two elements
for(i = 0; i < tempArray.length; i ++)
{
myarray[i] = tempArray[i].split(';');
myarray[i][1] = myarray[i][1].replace(/\"/g,'');
myarray[i][1] = myarray[i][1].replace(/\]/g,'');
myarray[i][0] = myarray[i][0].replace(/\[/g,'');
}
})
As much as I'm going to get flack for this (eval tends to be a security risk), I would just do
var myarray = eval("[" + result + "]");
You should use JSON to return data from your server to your JS script. That will be pretty easier to manipulate it as an array.

Javascript - clearing duplicates from an array object

Hi
I have a javascript array object rapresenting the amount of items sold in a given country, like this:
var data = [{'c1':'USA', 'c2':'Item1', 'c3':100},
{'c1':'Canada', 'c2':'Item1', 'c3':120},
{'c1':'Italy', 'c2':'Item2', 'c3':140},
{'c1':'Italy', 'c2':'Item2', 'c3':110}]
I need to avoid duplicates (as you may see, the last two 'records' have the same Country and the same Item) and sum the amounts; if I was getting data from a database I would use the DISTINCT SUM clause, but what about it in this scenario? Is there any good jquery trick?
You could use an object as a map of distinct values, like this:
var distincts, index, sum, entry, key;
distincts = {};
sum = 0;
for (index = 0; index < data.length; ++index) {
entry = data[index];
key = entry.c1 + "--sep--" + entry.c2;
if (!distincts[key]) {
distincts[key] = true;
sum += entry.c3;
}
}
How that works: JavaScript objects are maps, and since access to properties is an extremely common operation, a decent JavaScript implementation tries to make property access quite fast (by using hashing on property keys, that sort of thing). You can access object properties using a string for their name, by using brackets ([]), so obj.foo and obj["foo"] both refer to the foo property of obj.
And so:
We start with an object with no properties.
As we loop through the array, we create unique key from c1 and c2. It's important that the "--sep--" string be something that cannot appear in c1 or c2. If case isn't significant, you might throw a .toLowerCase in there.
If distincts already has a value for that key, we know we've seen it before and we can ignore it; otherwise, we add a value (true in this case, but it can be just about anything other than false, undefined, 0, or "") as a flag indicating we've seen this unique combination before. And we add c3 to the sum.
But as someone pointed out, your last two entries aren't actually the same; I'm guessing that was just a typo in the question...
jQuery may have an array function for this, but because your two Italy objects are not distinctly unique, your asking for a custom solution. You want to populate a array and check it for duplicates as you go:
var data = [{'c1':'USA', 'c2':'Item1', 'c3':100},
{'c1':'Canada', 'c2':'Item1', 'c3':120},
{'c1':'Italy', 'c2':'Item2', 'c3':140},
{'c1':'Italy', 'c2':'Item1', 'c3':110}]
var newArray = [];
var dupeCheck = {}; // hash map
for(var i=0; i < data.length; i++){
if(!dupeCheck[data[i].c1]){
newArray.push(data[i]);
dupeCheck[data[i].c1] = true;
}
}
test
HTML:
<div id="test"></div>
JS:
var data = [{'c1':'USA', 'c2':'Item1', 'c3':100},
{'c1':'Canada', 'c2':'Item1', 'c3':120},
{'c1':'Italy', 'c2':'Item2', 'c3':140},
{'c1':'Italy', 'c2':'Item1', 'c3':110}];
var
l = data.length, // length
f = "", // find
ix = "", // index
d = []; // delete
for (var i = 0; i < l; i++) {
ix = data[i].c1 + "_" + data[i].c2 + "__";
//var re = new RegExp(ix);
//if (re.test(f))
if (f.indexOf(ix) != -1)
d.push(i);
else
f += ix;
}
for (var i1 = 0; i1 < d.length; i1++){
$("#test").append("<div>for delete: "+d[i1]+"</div>");
}
EDIT
Although chrome works much faster, works only in chrome faster the example with indexOf, then in IE/Opera/Firefox/Safary works faster with an object.
The code created by "# TJ Crowder" is much more efficient.

Categories

Resources