How to get localStorage array data. - javascript

I am new to localStorage. I set array in localstorage so how can get this value. My code as below.
$scope.lineItemID = data.id;
var itemtemp={
"itemid": data.id,
"qty": $scope.quantity
};
var itemqty=JSON.parse(localStorage.getItem("itemqty")) || [];
itemqty.push(itemtemp);
localStorage.setItem("itemqty", JSON.stringify(itemqty));
So my question is how can I get itemqty.qty as per itemid from localstorage

try Below code
$.each(data.itemqty, function(index, item) {
// append data using html //use item.name
});
OR try below
$.each(data, function(idx, item){
// append data using html
//
});

You are quite simply creating an array of objects itemqty and saving it in the browser's storage. When you do this:
var itemqty=JSON.parse(localStorage.getItem("itemqty")) || [];
//itemqty is available to you as an array of objects.
Suppose you are looking for the associated quantity for some itemid stored in the variable foo. You just need to traverse the parsed itemqty like so:
$.each(itemqty, function( index, value ) {
if(value.itemid == foo)
{
console.log(value.qty);
// value.qty is the required quantity
}
});

items=JSON.parse(localStorage.getItem('itemqty'));
for (var i = 0; i < items.length; i++) {
if(items[i].itemid === itmId) {
return items[i].qty;
}
}
I am using it & it's working

Related

Find common id field between two seperate array object and merge it angular js

I have two separate data array objects with multiple fields:
This is how the data object array looks like with the eventId field in it too.
The annotateData object has eventId field that is also present in the data object. I want to check which data element has the same eventId present in the annotateData and then merge that annotateData element to the data object element. So the output will have data object with annotateObject fields added to it.
data: [{
0:{ annotateData fields + already present data fields} //if eventId matches
}]
Is there a more efficient way to do so rather than running the loop through the entire data object?
I don't think that there is another efficient way of doing this rather than looping. Although I would implement a few helper methods to iterate over and merge (as given here):
Array.prototype.indexOfWithKeyValue = function(key, value) {
var index = -1;
var _this = this;
for (var i = 0; i < this.length; i++) {
var item = _this[i];
if (item[key] === value) {
index = i;
break;
}
}
return index;
};
Array.prototype.find = function(key, value) {
var index = this.indexOfWithKeyValue(key, value);
return this[index];
};
And then iterate over:
var annotateData = []; // sample data
var data = []; // sample data
angular.forEach(annotateData, function(aData) {
var matchingData = data.find("eventId", aData.eventId);
if (matchingData) {
// Matching fields from "annotateData" will be merged over "data"
angular.merge(matchingData, aData);
}
});

Check json data for value and then get its key

I have some JSON data that I am retrieving from https://status.mojang.com/check and am storing in a variable. I'm still quite new to JSON/JS and I can't seem to find any answers on google.
Code:
function checkMojang() {
var mojangStatus = mojang.status();
mojangStatus.then(function (message) {
var response = JSON.parse(message);
})
}
Data I am using can be seen at the link above. I am trying to check all the data in the json array, see if any of the values contain "yellow" or "red" and get the keys for those values along with their checked value but can't figure out how to do so.
You can loop through the array and then through the object properties and make a new object using the colors as keys
var response = [{"minecraft.net":"green"},{"session.minecraft.net":"red"},{"account.mojang.com":"green"},{"auth.mojang.com":"green"},{"skins.minecraft.net":"green"},{"authserver.mojang.com":"yellow"},{"sessionserver.mojang.com":"green"},{"api.mojang.com":"green"},{"textures.minecraft.net":"green"},{"mojang.com":"red"}];
var new_response = {};
response.forEach(function(obj){
for (var prop in obj) {
if(obj.hasOwnProperty(prop)) {
if(new_response[obj[prop]] == undefined) new_response[obj[prop]] = [];
new_response[obj[prop]].push(prop);
}
}
})
console.log(new_response);
The you can use the object for your needs as
new_response["red"]
giving you the list of all key with red value.
you can use the method array.foreach() to execute a provided function once per array element and the for ... in to itarate over the enumarable properties.
So you can test the value and get keys for the value "yellow" or "red"
response.forEach(function(element) {
for (k in element) {
if (element[k]=="red" or element[k]=="yellow") {
// k is the key
}
}
});
function checkMojang() {
var mojangStatus = mojang.status();
mojangStatus.then(function (message) {
var response = JSON.parse(message);
for (i = 0; i < response.length; i++) { // iterate over response array
var item = response[i]; // get item from array
var key = Object.keys(item)[0]; // get the key of the item
var value = item[key]; // get the value of the item
if (value === 'yellow' || value === 'red') {
// do something, like adding it to a list
}
}
});
}

Getting value from json/javascript array of name/value pairs?

I have a JSON array of name/value pairs and I'm looking at a sensible way to be able to adjust the value for a particular name in the array. e.g.
var myArr = [{"name":"start","value":1},{"name":"end","value":15},{"name":"counter","value":"6"},{"name":"user","value":"Bert"}]
I can use
$.each(myArr, function (key, pair) {
if (pair.name == 'user')
{
pair.value = 'bob';
}
});
but in reality my object has tens of values and I would like to be able to change them much more simply than adding an if for each one.
Ideally myArr['user'].value = 'bob'; or something similar.
You have an array of objects in an array. An array does not have any indexing method that gives you direct lookup like you asked for;
myArr['user'].value = 'bob';
To get that, you would need to restructure your data so that you had an object where the name was the main key and inside that key was another object with the rest of your data for that user like this:
var myData = {
"start": {value: 1},
"end": {value: 15},
"user": {value: Bert}
};
The, you could directly access by name as in:
myData['user'].value = 'bob;
If you wanted to stick with your existing data structure, then the simplest thing I can think of is to make a simple function that finds the right object:
function findUser(data, nameToFind) {
var item;
for (var i = 0; i < myArr.length; i++) {
item = nameToFind[i];
if (item.name === nameToFind) {
return item;
}
}
}
var myArr = [{"name":"start","value":1},{"name":"end","value":15},{"name":"counter","value":"6"},{"name":"user","value":"Bert"}]
Then, you could do something like this:
findUser(myArr, "user").value = "bob";
This assumes you're only looking for data that is in the array because otherwise, this will create an error unless you add error checking to it.
If you just really want to turn the whole thing into a function that finds and changes the name, it can be like this:
function changeUser(data, nameToFind, newName) {
var item;
for (var i = 0; i < myArr.length; i++) {
item = nameToFind[i];
if (item.name === nameToFind) {
item.name = newName;
return;
}
}
}
I will award the points for the best answer, but I actually solved it a completely different way:
First build up a list of "names" in the order they appear:
var keys = [];
$.each(myArr, function (key, pair) {
keys.push(pair.name);
});
then I can use:
myArr[keys.indexOf('sEcho')].value = 'whatever';
Try This
$.grep(myArr,function(e){return e.name=="user"})[0].value="ppp"
You can use the $.greb() of jquery.
Add this function:
function SetArrayValue(arr, key, value, stopOnFirstMatch) {
for (var i=0; i<arr.length; i++) {
if (arr[i].name === key) {
arr[i].value = value
if (stopOnFirstMatch !== undefined && stopOnFirstMatch) return
}
}
}
Then use it this way:
SetArrayValue(myArr, 'user', 'bob')

Sort JSON array based on value with jQuery

I've got two dropdown select dropdowns: one for regions and one for cities in the selected region. The result is loaded by AJAX and in my response i get all cities in an JSON array:
{
1709: "Geertruidenberg",
1710: "Netersel",
1711: "Macharen",
1712: "Beers",
1713: "Hank",
1714: "Oudemolen",
1715: "Nistelrode"
}
I'm using this small plugin to load the data in the select dropdown:
(function($, window) {
$.fn.replaceOptions = function(options) {
var self, $option;
this.empty();
self = this;
$.each(options, function(index, option) {
$option = $("<option></option>")
.attr("value", index)
.text(option);
self.append($option);
});
};
})(jQuery, window);
And this piece of javascript to do the AJAX request:
$('select#Profile_regionId').change(function() {
$.post('/ajax/getcities', {regionid: $(this).val()}, function(data){
//console.log(data.cities);
$("select#Profile_cityId").replaceOptions(data.cities);
}, 'json');
});
All works totally fine, except the city dropdown is automatically sorted on the JSON array key. I tried to use the sort() method for this, but it won't work because it's an Object and not an array. Then i tried to create an array of it:
var values = [];
$.each(data.cities, function(index,value)) {
values[index] = value;
}
But for some reason, the dropdown list fills itself up from 1 to the first found id (key of array) of the city, and i don't know why it's doing that (array itself looks fine).
How can i sort the thing so my cities are ordered alphabetically in the dropdown list?
It needs to be converted to an array so that it can be sorted. Let's assume this is your object. Note that I rearranged it to be unsorted, to prove this works.
originalData = {
1712: "Beers",
1709: "Geertruidenberg",
1710: "Netersel",
1713: "Hank",
1714: "Oudemolen",
1711: "Macharen",
1715: "Nistelrode"
};
Now to create an array version we need to create an array, and insert objects into it. I'm calling the keys "year". Note that we're calling parseInt on the keys. Keys in JavaScript (except for arrays) are always strings. For example, {foo: "bar"} has a string key "foo". This also applies to numerical looking keys.
var dataArray = [];
for (year in originalData) {
var word = originalData[year];
dataArray.push({year: parseInt(year), word: word});
}
There's a chance that we have our data out of sort right now, so we manually sort it. Note that this is a case sensitive sort. For example, "Qux" comes before "foo".
dataArray.sort(function(a, b){
if (a.word < b.word) return -1;
if (b.word < a.word) return 1;
return 0;
});
The function now just pulls option.year and option.word from our array.
$.fn.replaceOptions = function(options) {
var self, $option;
this.empty();
self = this;
$.each(options, function(index, option) {
$option = $("<option></option>")
.attr("value", option.year)
.text(option.word);
self.append($option);
});
};
And then you finally use the plugin, passing the array. You can put all of this code in the plugin, if that works best for you.
$('#mylist').replaceOptions(dataArray);
fiddle
This will do what you want and take care of the empty ids/undefined values:
var data = {
1709: "Geertruidenberg",
1710: "Netersel",
1711: "Macharen",
1712: "Beers",
1713: "Hank",
1714: "Oudemolen",
1715: "Nistelrode"
};
var values = [];
$.each(data, function(index, value) {
values[index] = value;
});
values.sort();
$.each(values, function(index, value) {
if(value != undefined) {
$("#Profile_cityId").append("<option>"+ value +"</option");
}
});
Just replace the append I put in with your own function because jsFiddle was giving me trouble using that. Demo: http://jsfiddle.net/R4jBT/3/
So here is how I would do it. I assume that you are getting an AJAX response that comes like:
results: [
{year: 1709, city: "Geertruidenberg"},
{year: 1710, city: "Netersel"},
{year: ..., city: ...}
]
And, in a standard AJAX call, you would run through them like this, in a success function:
success: function(data) {
var results = data.results;
if (results.length > 0) {
for (i=0; i < results.length; i++) {
dataArrayOrig.push({
"id" : results[i].year,
"label" : results[i].city
});
}
}
},
I saw you say you do your call like this:
$.post('/ajax/getcities', {regionid: $(this).val()}, function(data){
//console.log(data.cities);
$("select#Profile_cityId").replaceOptions(data.cities);}, 'json');
You're not doing anything tests on data to see if it has results (ex. if (data.length > 0) { ... }), and you would need to push those results to an original array that stays pristine and another that can be sorted, then a final one that can get back the original year to the label, that the dropdown can then receive.
If you do it as I showed, above, you can integrate the lines I gave into the function(data){ ... } area.
Right after the push to the dataArrayOrig object, you can push to a new array you can use to sort with, using a comparison function to determine if the label (city) should come before or after the previous entry:
var results = data.results;
if (results.length > 0) {
for (i=0; i < results.length; i++) {
dataArrayOrig.push({
"id" : results[i].year,
"label" : results[i].city
});
dataArraySorting.push({
"id" : results[i].year,
"label" : results[i].city
});
dataArraySorting.sort(compare);
JSON.stringify(dataArraySorting); // sorted cities, but will be mismatched to the years
}
}
The comparison function:
function compare (a, b) {
if (a.label < b.label)
return -1;
if (b.label < a.label)
return 1;
return 0;
});
You could also do this inline:
dataArraySorting.sort(function(a, b){
if (a.label < b.label) return -1;
if (b.label < a.label) return 1;
return 0;
});
I prefer the function approach since then it can be re-used. We will see the usefulness of that in a minute.
For your arrays, declare them at the top, before your functions:
var dataArrayOrig = [];
var dataArraySorting = [];
var dataArraySorted = [];
So after that loop that goes through the results, start another one that goes through the "sorting" array and compares its label against the one in the original array we pushed to and pulls out the original ID (Year):
for (var j=0; j < dataArraySorting.length; j++) {
for (var k=0; k < dataArrayOrig.length; k++) {
if (dataArraySorting[j].label == dataArrayOrig[k].label) {
dataArraySorted.push({
"id" : dataArrayOrig[k].id,
"label" : dataArraySorting[j].label
});
console.log("Sorted ID: " + dataArrayOrig[k].id + ", Sorted label: " + dataArraySorting[j].label);
dataArraySorted.sort(compare);
JSON.stringify(dataArraySorted); // array of sorted cities, matched to year
}
}
}
You would go on to apply that dataArraySorted array to your dropdown as normal. I tested to see if I got more than 0 items from the original AJAX call, then I appended the options using id and label from the array's property names:
if (dataArraySorted.length > 0) {
$.each(dataArraySorted, function() {
$("#combobox").empty().append($("<option></option>").val(this['id']).html(this['label'));
});
}
JSFiddle with the results.

Get Length of json Data

i have this json data and i want to get length of this json data and also of css
my json data is shown here
jso({tag:"div",css:{backgroundColor:"red"},html:"abc"})
i have pass this in function
function jso(data){
alert(data.length)
}
Your JSON is not a valid JSON object
{
"tag": "div",
"css": {
"backgroundColor":"red"
},
"html":"abc"
}
However proper JSON object don't have a length attribute, so you need to iterate over them to calculate the length.
i know what u mean u just need to loop over your object with a counter variable
var x = {tag:"div",css:{backgroundColor:"red"},html:"abc"}
function objectLength(obj){
var counter = 0;
for(var i in obj)
{
counter +=1;
}
return counter
}
use it like this
alert(objectLength(x))
To iterate over the data using jQuery counting how many iterations you did do the following:
var data = {tag:"div",css:{backgroundColor:"red"},html:"abc"};
var count = 0;
$.each(data, function(key, value) {
count++;
});
See jsFiddle here.
To iterate over the data using JavaScript only counting how many iterations you did do the following:
var data = {tag:"div",css:{backgroundColor:"red"},html:"abc"};
var count = 0;
var key;
for(key in data)
{
var value = data[key];
count++;
}
​See jsFiddle here.

Categories