How to delete a specific item/object in localStorage? - javascript

Turns out that my localStorage["items"] stored my JSON as a string.
"["{\"itemId\":1, \"itemName\":\"item1\"}", "{\"itemId\":2, \"itemName\":\"item2\"}",
"{\"\":3, \"itemName\":\"item3\"}",]"
This is what it looks like when I JSON.parse(localStorage["items"]):
["{"itemId":1, "itemName":"item1"}", "{"itemId":2, "itemName":"item2"}"
"{"itemId":3, "itemName":"item3"}"]
So in my loop I made it into an object by using jQuery.parseJSON:
var object = jQuery.parseJSON(item[i]);
Right now, what I want to do is delete the object where itemId = 3 and make sure that the object is totally removed from the localStorage.
Here's my Javascript so far:
$("#button_delete").on("click", function(e){
e.preventDefault();
var items = JSON.parse(localStorage.getItem('items'));
for (var i = 0; i < items.length; i++) {
var object = JSON.parse(items[i]);
if(object.request_id == 3){
console.log(items)
delete items[i] // slice doesn't work not sure why
console.log(items)
}
}
item = JSON.stringify(items);
console.log(item);
localStorage.setItem('items', item);
})
UPDATED
When I click the button now, it will delete that item however it will not delete the comma before it.
When I check the localStorage["items"] in the browser it returns this:
"["{\"itemId\":1, \"itemName\":\"item1\"}","{\"itemId\":2, \"itemName\":\"item2\"}",null]"
I have another page that will display the info in the html and it returns the error:
Uncaught TypeError: Cannot read property 'itemId' of null.
So right now is there a way to check or search in localStorage["items"] specifically for ,null and remove it so that the error won't show?
Code on how I'm displaying the info in HTML:
var items = JSON.parse(localStorage.getItem('items'));
var itemsHTML = "";
for(var i = 0; i < items.length; i++){
var object = jQuery.parseJSON(items[i]);
var displayItemId = object.itemId;
var displayItemName = object.itemName;
itemsHTML += "<li id="+displayItemId+">"+displayItemName+"</li>";
}
$("#viewItemList").html(itemsHTML);

All the answers were right but you have to :
Parse the string in localStorage to JSON (you did that)
Remove the item you don't want (with slice() )
Make the JSON to string
Re-set it in the localStorage
So :
1.
var items = JSON.parse(localStorage.getItem("items")); // updated
2.
for (var i =0; i< items.length; i++) {
var items = JSON.parse(items[i]);
if (items.itemId == 3) {
items.splice(i, 1);
}
}
3.
items = JSON.stringify(items); //Restoring object left into items again
4.
localStorage.setItem("items", items);
Parsing to JSON and storing it as string is kinda annoying, but that's the way localStorage works.

Try this one.
$("#button_delete").on("click", function(e){
e.preventDefault();
var items = JSON.parse(localStorage["items"]);
for (var i = 0; i < items.length; i++) {
if(items[i].itemId == 3){
items.splice(i,1);
break;
}
}
})

If you know the key of the specific item - do it short and simple like this:
if (localStorage.getItem('key_to_remove') != null)
localStorage.removeItem('key_to_remove');

localstorage can contain strings only
So first you have to parse items from localstorage (like u do now)
Remove from it the element you don't want.
Serialize it to JSON one more time and store in localstorage.

Here is the approach
var items = localStorage["items"];
for (var i =0; i< items.length; i++) {
var item = JSON.parse(items[i]);
if (item.itemId == 3) {
items.slice(i);
break;
}
}
// Don't forget to store the result back in localStorage
localStorage.setItem("items", items);

eliminar(est: string) {
//estudiantes ES LA KEY
var items = JSON.parse(localStorage.getItem('estudiantes'));
for (var i = 0; i < items.length; i++) {
var item = items[i];
if(item.id == est){
items.splice(i,1);
}
}
items = JSON.stringify(items);
localStorage.setItem('estudiantes', items);
this.getAll();
}

Related

sort array or json on basis of a number/object in javascript

I am facing an issue with sorting in JSON.I have a list which can reorder and the reordering can be saved so next time whenever user will come he/she can see the reordered list the way he arranged. The image is below.
Now it get save in object the order and when he retrieve it back the JSON is coming in this way.,you can see object ResourceSortedOrder is the order which telling that on which position item will be present it will come for the checked item only the rest will have null.Now on the basis of it I am sorting the array/JSON the javascript is below:
for (var i = 0; i < lst.length; i++) {
if (lst[i].ResourceSortedOrder != null) {
var temp = lst[i];
lst.splice(i, 1);
lst.splice(temp.ResourceSortedOrder, 0, temp);
lst.join();
}
}
It is getting sorted but the first element which has to place at 5th position is getting placed at the 4th position because of the data above it 100srvc resources is below it in JSON. So I am getting a result like below image.
Instead of my initial image.Please help
the JSON in string:
"[{"__type":"BusinessLayer.DTOApptResource","ResourceInClinicID":null,"ResourceInClinicName":null,"ResourceID":"d322a490-60ba-4739-a4ce-7d1de52f1789","ResourceName":"Dr. Maity","ResourceType":"Staff","ResourceRoster":[],"ResourceNotAvailableFrom":"0001-01-01T00:00:00.000Z","ResourceNotAvailableTo":"0001-01-01T00:00:00.000Z","ResourceSortedOrder":5,"ResourceKey":"Staff:d322a490-60ba-4739-a4ce-7d1de52f1789"},{"__type":"BusinessLayer.DTOApptResource","ResourceInClinicID":null,"ResourceInClinicName":null,"ResourceID":"e7217073-0763-4c42-8da0-7b4ce81f886a","ResourceName":"Dr. Shome","ResourceType":"Staff","ResourceRoster":[],"ResourceNotAvailableFrom":"0001-01-01T00:00:00.000Z","ResourceNotAvailableTo":"0001-01-01T00:00:00.000Z","ResourceSortedOrder":1,"ResourceKey":"Staff:e7217073-0763-4c42-8da0-7b4ce81f886a"},{"__type":"BusinessLayer.DTOApptResource","ResourceInClinicID":null,"ResourceInClinicName":null,"ResourceID":"670a9ec7-7502-4710-91d3-1c0dbe3023be","ResourceName":"TEST NEW DSHOME","ResourceType":"Staff","ResourceRoster":[],"ResourceNotAvailableFrom":"0001-01-01T00:00:00.000Z","ResourceNotAvailableTo":"0001-01-01T00:00:00.000Z","ResourceSortedOrder":2,"ResourceKey":"Staff:670a9ec7-7502-4710-91d3-1c0dbe3023be"},{"__type":"BusinessLayer.DTOApptResource","ResourceInClinicID":null,"ResourceInClinicName":null,"ResourceID":null,"ResourceName":null,"ResourceType":null,"ResourceRoster":null,"ResourceNotAvailableFrom":"0001-01-01T00:00:00.000Z","ResourceNotAvailableTo":"0001-01-01T00:00:00.000Z","ResourceSortedOrder":null,"ResourceKey":":"},{"__type":"BusinessLayer.DTOApptResource","ResourceInClinicID":null,"ResourceInClinicName":null,"ResourceID":"","ResourceName":"Hair care","ResourceType":"NonStaff","ResourceRoster":null,"ResourceNotAvailableFrom":"0001-01-01T00:00:00.000Z","ResourceNotAvailableTo":"0001-01-01T00:00:00.000Z","ResourceSortedOrder":null,"ResourceKey":"NonStaff:Hair care"},{"__type":"BusinessLayer.DTOApptResource","ResourceInClinicID":null,"ResourceInClinicName":null,"ResourceID":"","ResourceName":"New appointment","ResourceType":"NonStaff","ResourceRoster":null,"ResourceNotAvailableFrom":"0001-01-01T00:00:00.000Z","ResourceNotAvailableTo":"0001-01-01T00:00:00.000Z","ResourceSortedOrder":0,"ResourceKey":"NonStaff:New appointment"},{"__type":"BusinessLayer.DTOApptResource","ResourceInClinicID":null,"ResourceInClinicName":null,"ResourceID":"","ResourceName":"100 SRVC","ResourceType":"NonStaff","ResourceRoster":null,"ResourceNotAvailableFrom":"0001-01-01T00:00:00.000Z","ResourceNotAvailableTo":"0001-01-01T00:00:00.000Z","ResourceSortedOrder":null,"ResourceKey":"NonStaff:100 SRVC"},{"__type":"BusinessLayer.DTOApptResource","ResourceInClinicID":null,"ResourceInClinicName":null,"ResourceID":"","ResourceName":"Dressing","ResourceType":"NonStaff","ResourceRoster":null,"ResourceNotAvailableFrom":"0001-01-01T00:00:00.000Z","ResourceNotAvailableTo":"0001-01-01T00:00:00.000Z","ResourceSortedOrder":null,"ResourceKey":"NonStaff:Dressing"},{"__type":"BusinessLayer.DTOApptResource","ResourceInClinicID":null,"ResourceInClinicName":null,"ResourceID":"","ResourceName":"Hair care","ResourceType":"NonStaff","ResourceRoster":null,"ResourceNotAvailableFrom":"0001-01-01T00:00:00.000Z","ResourceNotAvailableTo":"0001-01-01T00:00:00.000Z","ResourceSortedOrder":null,"ResourceKey":"NonStaff:Hair care"},{"__type":"BusinessLayer.DTOApptResource","ResourceInClinicID":null,"ResourceInClinicName":null,"ResourceID":"","ResourceName":"smoothening","ResourceType":"NonStaff","ResourceRoster":null,"ResourceNotAvailableFrom":"0001-01-01T00:00:00.000Z","ResourceNotAvailableTo":"0001-01-01T00:00:00.000Z","ResourceSortedOrder":null,"ResourceKey":"NonStaff:smoothening"}]"
result is the result.
sort function is not used .
var checked = [];
var unchecked = [];
lst.map(function(item){
if(item.ResourceSortedOrder !== null){
checked.push(item);
}else{
unchecked.push(item);
}
});
var result = [];
checked.map(function(item){
result[item.ResourceSortedOrder] = item;
});
var index = 0;
unchecked.map(function(item){
while(result[index]){
index ++;
}
result[index] = item;
});
Use below code instead of for loop to sort "lst".
lst.sort(function (a, b) {
var a1 = a.ResourceSortedOrder, b1 = b.ResourceSortedOrder;
a1 = a1 == null ? 99999 : a1;
b1 = b1 == null ? 99999 : b1;
return a1 - b1 ;
});
This code will place the item in list as specified in "ResourceSortedOrder".
var sortedList = [];
for (var i = 0; i < lst.length; i++) {
var count = lst.length - sortedList.length;
var item = null;
for (var j = 0; j < count; j++) {
if (lst[j].ResourceSortedOrder == i) {
item = lst[j];
break;
}
}
if (item != null) {
sortedList.push(item);
}
else {
sortedList.push(lst[i]);
}
}
lst = sortedList;

Remove data from an array comparing it to an other array

I am trying to compare the items in "item" array and the copyofOpList array to retrieve the data occurrences in copyofOpList
this is my try:
var _deleteUsedElement1 = function(item) {
for (var i = 0; i < item.length-1; i++){
for (var j = 0; j< $scope.copyofOpList.length-1; j++){
if (item[i].operationCode == $scope.copyofOpList[j].code) {
$scope.copyofOpList.splice(j, 1);
} } } };
$scope.compareArrays = function() {
...Get data from web Service
_deleteUsedElement1(item);
}
the copyofOpList array has 14 elements,and the item array has 2 array
but my code deletes only one occurrence (the first),so please how can I correct my code,to retrieve any occurances in the copyofOpList array comparing to the item array
thanks for help
I'd try to avoid looping inside a loop - that's neither a very elegant nor a very efficient way to get the result you want.
Here's something more elegant and most likely more efficient:
var item = [1,2], copyofOpList = [1,2,3,4,5,6,7];
var _deleteUsedElement1 = function(item, copyofOpList) {
return copyofOpList.filter(function(listItem) {
return item.indexOf(listItem) === -1;
});
};
copyofOpList = _deleteUsedElement1(item, copyofOpList);
console.log(copyofOpList);
//prints [3,4,5,6,7]
}
And since I just noticed that you're comparing object properties, here's a version that filters on matching object properties:
var item = [{opCode:1},{opCode:2}],
copyofOpList = [{opCode:1},{opCode:2},{opCode:3},{opCode:4},{opCode:5},{opCode:6},{opCode:7}];
var _deleteUsedElement1 = function(item, copyofOpList) {
var iOpCodes = item.map(function (i) {return i.opCode;});
return copyofOpList.filter(function(listItem) {
return iOpCodes.indexOf(listItem.opCode) === -1;
});
};
copyofOpList = _deleteUsedElement1(item, copyofOpList);
console.log(copyofOpList);
//prints [{opCode:3},{opCode:4},{opCode:5},{opCode:6},{opCode:7}]
Another benefit of doing it in this manner is that you avoid modifying your arrays while you're still operating on them, a positive effect that both JonSG and Furhan S. mentioned in their answers.
Splicing will change your array. Use a temporary buffer array for new values like this:
var _deleteUsedElement1 = function(item) {
var _temp = [];
for (var i = 0; i < $scope.copyofOpList.length-1; i++){
for (var j = 0; j< item.length-1; j++){
if ($scope.copyofOpList[i].code != item[j].operationCode) {
_temp.push($scope.copyofOpList[j]);
}
}
}
$scope.copyofOpList = _temp;
};

Constructing json object using javascript

I am facing issues while constructing an object using javascript. I want this:
{
"p_id": "2",
"p_name": "weblogic",
"ip_list": [
{
"ip_id": 2690
},
{
"ip_id": 2692
},
{
"ip_id": 2693
}
]
}
Below is the javascript code that I am using to get the data into the object:
var ipArray = [];
secTagJSON.p_name = "weblogic";
secTagJSON.p_id = "2";
for (var index=0; index < selectedArray.length; index++){
secTagJSON.ip_list.push("ip_id": selectedArray[index]);
}
I am able to construct the properties for p_id and p_name but struggling to create the the ip_list. Please let me know how to get this constructed using javascript.
Code for posting to the server:
var ipArray = [];
secTagJSON.p_name = "weblogic";
secTagJSON.p_id = 2;
for (var index=0; index < selectedArray.length; index++){
secTagJSON.ip_list.push({"ip_id": selectedArray[index]});
}
console.log (secTagJSON);
console.log (JSON.stringify(secTagJSON));
$http.post("http://server:port/api/v1/tags").
success(function(data) {
console.log (data)
});
Simply do this:
var obj = { ip_list: [] };
obj.p_name = "weblogic";
obj.p_id = "2";
for (var i = 0, j = selectedArray.length; i < j; i++)
obj.ip_list.push({ ip_id: selectedArray[i] });
Note that your ip_list is actually an array of objects. So, when you iterate over it, remember that each var item = json.ip_list[i] will return an object, that you can access its properties using: item['ip_id'].
Note that obj is an Javascript object, it is not an JSON. If you want the JSON, you can use JSON.stringify(obj). This will return your JSON (string).
Hope I've helped.
Try:
secTagJSON.p_name = "weblogic";
secTagJSON.p_id = "2";
secTagJSON.ip_list = [];
for (var index=0; index < selectedArray.length; index++){
secTagJSON.ip_list.push({"ip_id": selectedArray[index]});
}
you forgot your {} around "ip_id": etc...
You also need to declare that ip_list is an array.
Your ip_list is an array of objects. I would guess that your script was not running as it was.
Posting to your server you should use:
$http.post('server:port/api/v1/tags', secTagJSON).sucess(...

How to remove an object in a JSON object?

Let me explain.
I got this JSON with many objects:
data = [{"id":"784","label":"blah","publisher":"me"},{"id":"785","label":"bleh","publisher":"you"},{"id":"786","label":"blih","publisher":"she"}];
Ex: I want to remove the object where id = 785
I tried:
$.each( data, function( key, value ) {
if(value.id == '785'){
delete data[key];
}
});
It works, but it changes 'data' structure. Now it seems like this:
data = ["0":{"id":"784","label":"blah","publisher":"me"},"2":{"id":"786","label":"blih","publisher":"she"}]
I'm working with a plugin that does not accept this structure(jQuery UI Autocomplete). So I need to remove the object without changing the 'data' structure.
Any help?
Another way to do it is using filter on the array:
var data = [{"id":"784","label":"blah","publisher":"me"},{"id":"785","label":"bleh","publisher":"you"},{"id":"786","label":"blih","publisher":"she"}];
var result = data.filter(function(x){return x.id !== '785'; });
HTH
That's an array of objects, so try:
for (var i = 0; i < data.length; i++) {
if (data[i].id == 785) {
data.splice(i, 1);
break;
}
}
Try this (fiddle: http://jsfiddle.net/U94Ym/1/):
var i = 0;
while (i < data.length) {
if (data[i].id === "785") {
data.splice(i, 1)
}
else {
i++;
}
}

Merge two intersecting arrays into a HashMap, One Key & Multiples values

I'm trying to make a basic calendar to help automate Timesheets at work using Angular.js and Chrome Extensions, but for now I am stuck on this part.
Below you can see two arrays: pastTwoWeeks which is a list of dates from today back 14 days and Timesheet entries which were retrieved from an API - these will actually be objects with many properties but for now I am just using a simple date.
Here's a jsfiddle, am I on the right track? Thanks
http://jsfiddle.net/v599n/
var pastTwoWeeks = ['15/10/2013', '14/10/2013', '13/10/2013',
'12/10/2013', '11/10/2013', '10/10/2013',
'09/10/2013', '08/10/2013', '07/10/2013',
'06/10/2013', '05/10/2013', '04/10/2013',
'03/10/2013', '02/10/2013'];
var entries = ['11/10/2013', '11/10/2013', '11/10/2013',
'11/10/2013', '10/10/2013', '10/10/2013', '10/10/2013',
'09/10/2013', '09/10/2013', '09/10/2013', '08/10/2013',
'08/10/2013', '07/10/2013', '07/10/2013', '04/10/2013',
'04/10/2013', '03/10/2013', '03/10/2013', '02/10/2013',
'02/10/2013', '02/10/2013', '02/10/2013', '01/10/2013',
'01/10/2013', '01/10/2013'];
var calander = {};
for(var j=0; j< pastTwoWeeks.length; j++) {
var key = pastTwoWeeks[j];
if (key in calander == false) {
calander[key] = {};
}
for(var i = 0; i< entries.length; i++) {
var entry = entries[i];
if(entry === key){
calander[key][entry];
console.log(key + " " + entry);
}
}
}
What I want to achieve:
15/10/2013
14/10/2013
13/10/2013
12/10/2013
11/10/2013 (4 entries)
11/10/2013
11/10/2013
11/10/2013
11/10/2013
etc...
Here's a jsfiddle, am I on the right track?
Not really.
calander[key] = {};
I think you rather want an array of entries here, not an object.
calander[key][entry];
This does not do anything. If you were trying to create a property, you would need to assign to it. Also, since all entrys are the same for a key, you would only overwrite the one and same property. Better .push() to an array.
for(var j=0; j< pastTwoWeeks.length; j++) {
for(var i = 0; i< entries.length; i++) {
if(entry === key)
That's rather inefficient. You can do better by executing the loops after each other, and just check whether your entry exists as a key of your calender which was previously filled with the pastTwoWeeks.
var calendar = {};
for (var i=0; i<pastTwoWeeks.length; i++) {
var key = pastTwoWeeks[i];
calendar[key] = [];
}
for (var i=0; i<entries.length; i++) {
var entry = entries[i],
key = entry; // this might change for more complex objects
if (key in calendar) {
calendar[key].push(entry);
console.log(entry+" added to calendar at " + key);
}
}
Something like this should do what your looking for:
var pastTwoWeeks = ['15/10/2013', '14/10/2013', '13/10/2013', '03/10/2013', '02/10/2013'];
var entries = ['11/10/2013', '11/10/2013', '11/10/2013', '01/10/2013', '01/10/2013'];
var calander = {};
pastTwoWeeks.forEach(function(date) {
calander[date] = [];
});
entries.forEach(function(date) {
if (calander[date] === undefined) calander[date] = [];
calander[date].push(date);
});

Categories

Resources