Dynamically remove and add strings in localstorage [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm currently working on a HTML5 project and I need to use localstorage.
I want to be able to dynamically remove items from my localstorage. This means that if I have five items, and I want to remove the second item, the third, fourth and fifth item will be automatically allocated to a lower place so that I don't have a gap left (as this is very annoying when I want to print my whole local storage).

HTML5 localStorage aka Web Storage, uses keys to store string values. So you can store objects or arrays by converting them to JSON before storing:
// define an array of objects
var arr = [
{ name : 'first', description : 'first description' },
{ name : 'second', description : 'second description' },
{ name : 'third', description : 'third description' }
];
// store the array to localStorage as a JSON string
localStorage.setItem("data", JSON.stringify(arr));
// retrieve the JSON from localStorage and parse it back to an array
var arr = JSON.parse(localStorage.getItem("data"));
// remove the second object from the array
arr.splice(1, 1);
// let's update the first object too
arr[0].name = 'first name';
// save it back to localStorage
localStorage.setItem("data", JSON.stringify(arr));

if (localStorage.text)
{
var text1 = localStorage.text;
var splitText1 = text1.split(',');
if (splitText1.length > 0)
for (i in splitText1)
{
var div = document.createElement("div");
div.setAttribute("id", "medicament");
div.innerHTML = "<h1>" + splitText1[i] + "</h1>"; document.body.appendChild(div);
}
}
This is the code we use to print things on our screen.

You can use jstorage to solve your problem.

Related

How do I check for property2 value in the same item after property1 value passes a condition? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
This is how my array is set up:
"members" : [
{ "health" : 0,
"stateStr" : "Not reachable",
},
{ "health" : 1,
"stateStr" : "PRIMARY",
},
{ "health" : 1,
"stateStr" : "ARBITER",
}
],
What I'm trying to achieve is to iterate through all 3 members, and find if a member has stateStr = Primary (in the above example, member[1] will pass this condition). If that condition passes, look at the same member and see if health=1. In the above example, I would then look at if member[1].health =1. I'm not sure how to store that index of member.. I would appreciate it if you could show me exactly - I'm very new!
Here's the logic of it:
If any member has stateStr=Secondary. If yes, then print
"Secondary node is still running." and break.
Else, Check if any member has stateStr="Primary". If Primary is found, check whether its health = 1
If none of the members are Primary, then print "No primary node
found" and if Primary node is found but its health !=1, then print
"Primary node unhealthy" and break.
Repeat the previous three steps for stateStr="Arbiter"
Arrays in JavaScript can be iterated through with a for-loop.
for (var i = 0; i < members.length; i++) {
if (members[i].stateStr == "PRIMARY") { // 1st condition
if (members[i].health === 1) { // 2nd condition
// store index i here
}
}
}
Understand that in the above for-loop, members[i] only gets the element containing the JSON object. We must then specify the JSON property after a period.
The way a JSON object works in this case is by indicating the JSON property name after a period for that element of the array. In simple terms, it works this:
members[i].JSON_PROPERTY
See this question and this on more about iterating through arrays with JSON. There is more than one way to do this too. This one is fairly common.
Lastly, remove the comma , at the end of the members array in the declaration. it should end with a ; since it's the end of the array declaration:
{ "health" : 1,
"stateStr" : "ARBITER",
}
];

Adding array into an certain array index [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I want to populate a nested array.
The first array option_array is created like this
var option_array =[];
if(!option_array.includes(row.option.option_id))
{
option_array .push({
option_id:row.option.option_id,
option_name:row.option.option_name,
max:row.option.max,
min:row.option.min,
value:row.option.value,
price:row.option.price
})
}
And now, I am creating another array option_group
var option_group=[];
if(!option_group.includes(row.option_group_id))
{
option_group.push({
option_group_id:row.option_group_id,
option_group_name:row.option_group_name,
max:row.max,
min:row.min,
option:option_array
})
}
And I want to modify option_group whereas it will add only option:option_array where current row.option_group_id is equal to the option_group.option_group.option_group_id
.includes checks if the array includes a certain item. Since you have an array of objects, you can't check if the array includes row.option_group_id. You can use find instead. Get the object with row.option_group_id from the array. If it exists, update it. Else, add a new object to the array
const found = option_group.find(a => a.option_group_id == row.option_group_id)
if (found) {
found.option = row.option_array; // update the found object
} else {
option_group.push({
option_group_id: row.option_group_id,
option_group_name: row.option_group_name,
....
})
}

Create a nested array? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
I'm creating a trivia game which will give the user 4 answer to pick from. Is using an array to include the question and the answer a good option for this game? and if so what is the proper way to create a nested array.
So... in js it's not a problem to make a nested array, but it is a problem if you're thinking of key => value type of array, in that case you need to use an object, you can foreach it's properties as you would with array IF you'd need to. You can store answer values in array (I've been there with exactly the same thing you want to do so trivia learning game), but you can always use objects and do something like that
var userAnswer = 'something',
item = {
question: 'what is a?'
answers: [ 'a', 'b', 'c' ]
validAnswer: 0;
}
if(userAnswer === item.answers[validAnswer]) {
console.log("is valid");
}
some other usage:
var userStats = {
status: 'alive',
makeDead: function() {
this.status = 'dead';
},
bringBackToLife: function() {
this.status = 'alive';
},
}
//then you can even do things like...
userStats.makeDead();
console.log(userStats); //user will be dead
userStats.bringBackToLife(); //user status will be alive
I mean you should be fine with array for keeping just question or question and (nested[[]]) array of answers, but then you're starting to play game of array[0] (should be question right?) array[3] (should be invalid answer?) and then what? if you still think your trivia game will never grow then you might stick to that solution, but if you think it might ever evolve just use objects to keep stuff organised.
update
Try to keep your objects small & dont make 'god' objects (look up SOLID rules), though if you want to let's say save/have a lesson containing some questions then you could have one big object containing a lot of small ones, i.e.
//you can make object to store some data and functions
var LessonItem = function(question){
this.question = question;
this.answers = [];
this.addAnswer = function(answer){
this.answers.push(answer);
};
};
//you dont need the 'valid' part if there's always just one valid option
var question1 = new LessonItem('What is?');
question1.addAnswer({text: 'It is something', valid: true });
question1.addAnswer({text: 'It is something not', valid: false });
question1.addAnswer({text: 'It is something 3', valid: true });
//and this would be our 'big' object, i.e. to save in json file or whatever
var lesson = {
lesson_subject: 'something',
lesson_repeat: 3,
lesson_score: 124,
lesson_items: [
question1,
//question2
]
};
console.log(lesson);
but yeah, you can have big 'object' to 'store' others, but avoid creating god-like one huge objects managing everything cause it will become hell with time :D as well im not sure if you're doing that but you can paste in your javascript in google chrome tools console and check if it's working right without reloading page... (for quick checks :))

Proper array structure [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Commonly, arrays are formed like var array = ["some","string","elements"] or var array = [1, 2, 3]. Been searching for times, but I haven't seen articles that may clear my mind. Now, is it possible to have an array structure like var array = [some, string, elements]. As what can be observed, it was somehow a string without "".
To visualize my concern, I have this code
var data = []
for (var x = 0; x < arrayData.length; x++){ //arrData contains [1,2] structure
data.push("$scope.item["arrayData[x]"]");
}
//which gives var data = ["$scope.item[1], $scope.item[2]"]
I needed that var data to form like var data = [$scope.item[1],$scope.item[2]]. Is it possible?
EDIT
My bad, I haven't explained my query fully. The "$scope.item[" is a string, that's why I encapsulated it to ""
EDIT II
Is it possible to have an array structure like var array = [some, string, here]. Consider that some,string and here are not variables.
Don't complecate it, Just go with using JSON.stringify();
Your code should be
data.push(JSON.stringify("$scope.item[" + arrayData[x] + "]"));
You cannot have an array structure like var array = [some, string, elements]. There should be variables named some, string and elements.
$scope is a special variable in AngularJS. So, you should use it without "s. For example:
data.push($scope.item[arrayData[x]]);

Matching Array numbers with Array names? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
My programming lab problem statement:
Design an algorithm that will prompt for and receive an employee number from an operator at a terminal. your program is to search an array of valid employee numbers to check that the employee number is valid, look up a parallel array to retrieve the corresponding employee name for that number, and display the name to the screen. If the employee number is not valid, an error message is to be displayed.
I'm supposed to enter the employee number, and then it displays the employee name. (also need to give an error message if the number is invalid.)
var Emp_num = new Array(123,234,345,456,567,678,789,890,901,012);
var Emp_name = new Array("ED","BOB","LOU","JEAN","MAX","SUE","VIC","TOM","CAL","MO");
var i = 1;
Emp_num=prompt("Enter Employee Number: ");
You can't assign the return value from prompt to Emp_num because that's where you're storing the array of your employee numbers. Create a new variable named Req_num or something and store it there.
Then you'd just convert the user entry to an integer with parseInt and find the indexOf that number in Emp_num. You could then look up this index in Emp_name (if it's greater than -1) to get the employee name, like this:
var Emp_num = new Array(123,234,345,456,567,678,789,890,901,012);
var Emp_name = new Array("ED","BOB","LOU","JEAN","MAX","SUE","VIC","TOM","CAL","MO");
var Req_num = prompt("Enter Employee Number: ");
var Emp_idx = Emp_num.indexOf(parseInt(Req_num, 10));
if (Emp_idx > -1) {
alert("Employee name: " + Emp_name[Emp_idx]);
} else {
alert("Employee number not found.");
}
parseInt docs, indexOf docs
See demo

Categories