Get localstorage value from dynamic key - javascript

I have trawled the net and stackoverflow for an answer to this question.
How does one retrieve a value from a dynamic key which is also nested in localstorage.
I have tried numerous examples and seem to be getting nowhere.
I knwo a loop is required to perform the task but which type.
How do I get the 'uniqid' value which has the nested dynamic key SCI-4 from localstorage which reads:
simpleCart_items:{"SCI-4":{"quantity":4,"id":"SCI-4","price":8,"name":"12 fried chicken","flavours":"cola","code":"1001","cartid":"561","uniqid":"592dcd08b5fcc"}}
This allows me to view localstorage.
var obj = localStorage;
Object.keys(obj).forEach(function(key){
var value = obj[key];
console.log(key + ':' + value);
});
How do I iterate to get any value?
The difference in this question is that I seek to get the value from a nested key that has a dynamic value. If the key is not known how does one pull the value? What should the loop look like?

After a good nights sleep.
I am able to make headway. Thank you for pointing me in the right direction guys.
There are many opinions and ways to do some of these functions which got confusing.
localStorage needed to be accessed properly as I show below.
The issue is mostly resolved with:
var obj = JSON.parse(localStorage.simpleCart_items);
Object.keys(obj).forEach(function (key) {
Object.keys(obj[key]).forEach(function (val) {
//console.log(val);
if (val === "quantity")
{
//logic here
console.log(obj[key][val]);
}
});
});

think this is what your're looking for, :)
Object.keys(obj).forEach(function (key) {
Object.keys(obj[key]).forEach(function (val) {
//console.log(val);
if(val === "uniqid")
{
//logic here
console.log(obj[key][val]);
}
});
});

If you just store your structure as a single value for a single key, it's pretty easy to extract it later.
// How do I get the 'uniqid' value which has the nested dynamic key SCI-4 from localstorage which reads:
// This is our simulated result from pulling from localStorage
var lsString = `{
"simpleCart_items": {
"SCI-4": {
"quantity":4,
"id":"SCI-4",
"price":8,
"name":"12 fried chicken",
"flavours":"cola",
"code":"1001",
"cartid":"561",
"uniqid":"592dcd08b5fcc"
}
}
}`;
// First, remember that localStorage stores strings, so we must parse the string
// back into an object:
var lsObj = JSON.parse(lsString);
var keyName = Object.keys(lsObj.simpleCart_items).toString();
// Now, we can go directly to the property we want:
console.log(lsObj.simpleCart_items[keyName].uniqid);

Related

How to remove one value from a key in localstorage that has many values?

I've seen this question asked before but the solutions didn't help me hence why i've asked it again.
Currently, I am storing values into an array and that array is getting stored into localstorage.
This is the object
data.items -
0: {id: 190217270, node_id: 'MDEwOlJlcG9zaXRvcnkxOTAyMTcyNzA=', name: '3-Bit-CNC-Starter-Pack'}
1: {id: 187179414, node_id: 'MDEwOlJlcG9zaXRvcnkxODcxNzk0MTQ=', name: 'inb-go}
I have mapped through this and used 'name' as the value. I am calling this value through a button using this function
const favs = [];
function checkId(e) {
if (e.target.value !== ""){
if (!favs.includes(e.target.value)){
favs.push(e.target.value);
localStorage.setItem("name", JSON.stringify(favs));
console.log(favs);
document.getElementById("favsarray").innerHTML = favs;
}
}
}
and to remove the value from localstorage I am using this function.
function removeId(e, value) {
if (e.target.value !== "") {
favs.pop(e.target.value);
console.log(favs);
document.getElementById("favsarray").innerHTML = favs;
const stored = JSON.parse(localStorage.getItem("name"));
delete stored[value, e.target.value];
localStorage.setItem("name", JSON.stringify(stored));
console.log(stored);
}
}
Although the value is being removed from the array, it is not being removed from localstorage.
side note - I am calling this function with a separate button.
console log
array (item is gone)
[]
localstorage (the value is still there)
[
"Spiral-Up-Cut-Router-Bit"
]
But if I select another item to be added to localstorage, then the previous item gets removed.
UNFAVORITE - FUNCTION REMOVEid
[
"Spiral-Up-Cut-Router-Bit"
]
NEW FAVORITE - FUNCTION NEWId
[
"graphqless"
]
I hope this makes sense, I tried to add detail to it as best as possible.
Try to use localStorage.removeItem method to remove item from storage:
function removeId(e, value) {
if (e.target.value !== "") {
favs.pop();
// other code here
localStorage.removeItem('name'); // method to remove item from storage
}
}
UPDATE:
If an item is removed from array and we want to set this updated value to localstorage, then we can just update this value:
function removeId(e, value) {
if (e.target.value !== "") {
favs.pop();
console.log(favs);
document.getElementById("favsarray").innerHTML = favs;
const stored = JSON.parse(localStorage.getItem("name"));
delete stored[value, e.target.value]; // this code looks very fishy - charlietfl
localStorage.setItem("name", JSON.stringify(favs));
console.log(stored);
}
}
The easiest way is to just overwrite the item in localStorage. Once you remove the item from the favs array, call localStorage.setItem("name", JSON.stringify(favs)); again and you're done.
I am not sure whether this will help you but anyway I am sharing.
I don't understand this part of the abovementioned code:
delete stored[value, e.target.value];
What are you passing in the value and e.target.value? If it is the name ("Spiral-Up-Cut-Router-Bit") itself then the delete won't remove the value from the array. Usually, when you use the delete operator on the JS array you need to pass the index of the value, not the value itself.
Also, When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array.
When the delete operator removes an array element, that element is no longer in the array.
You can refer to the above output image, when I deleted the array values using the value even though its output is true it does not delete the value from the array. But when I used the index value for the delete, it deleted the value from the array.
Note: The array just removed the value but did not clear the index.
Maybe, you should use splice to remove specific values from the array and store the new array into the storage.
Also, the delete operator works well with JS objects. If you want to read more about this you can go to this link.✌🏼
Delete using splice:
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; trees.splice(3,1); console.log(trees);
As suggested, use splice (which will also update the Array's length) to delete the entry from the Array.
const stored = JSON.parse(localStorage.getItem("name"));
const index = stored.indexOf(nameValue);
if (index !== -1) {
stored.splice(index, 1);
localStorage.setItem("name", JSON.stringify(stored));
}
See:

push only unique values into array

not able to check the unique values log showing all values getting
added to the array
.
var moveToReady = [];
var topLinesRecords = new GlideRecord('x_snc_ms_dynamics_d365_queue');
topLinesRecords.addEncodedQuery('root_element_sys_id=03133e1a1bfe6410f8ca0e16624bcba7');
topLinesRecords.orderByDesc('sys_created_on');
topLinesRecords.query();
while(topLinesRecords.next()){
gs.info(' first record : ' + topLinesRecords.number);
if(moveToReady.indexOf(topLinesRecords.getValue('object_sys_id')) == -1){
moveToReady.push(topLinesRecords.getValue('object_sys_id'));
}
gs.info('array. : ' + moveToReady);
updateRecordtoFail(topLinesRecords);
}
You can use the Set structure from ES6 to make your code faster and more readable:
// Create Set
this.items = new Set();
add(item) {
this.items.add(item);
// Set to array
console.log([...this.items]);
}
you may use array.includes
if (!moveToReady.includes(topLinesRecords.getValue('object_sys_id'))){
moveToReady.push(topLinesRecords.getValue('object_sys_id'));
}
So, some tips to get unique values on ServiceNow:
-GlideRecord has a "getUniqueValue" method
(URL: https://docs.servicenow.com/bundle/paris-platform-administration/page/administer/table-administration/concept/c_UniqueRecordIdentifier.html)
-You can search on your Script Includes a OOB method/function to get only unique values. Search for "utils". Every instance has this, maybe "ArrayUtils".
Hope this information helped!

Finding elements in an array of objects where you have a bigger key

I'm writing a tiny reactive framework where I need to find out which subscriber needs updating. I'm implementing deep binding and I'm running into a wall how to find subscribers in an effective manner.
A stored variable can be an object, so for example
{
"user": {
"preferences": {
"food": "vegetarian"
}
}
}
You can get content to any level of this variable like this
getVar("user_preferences_food");
getVar("user_preferences");
However, you can also update it like that
setVar("user_preferences_food", "meat");
setVar("user_preferences", {"food": "meat"});
But in case of the first setVar (user_preferences_food) how can I find the subscriber using getVar("user_preferences"); or even getVar("user"); most effectively.
I already got it working by splitting the var on _ and then one by one concatting the next level and merging all the resulting arrays. But this is very resource intensive. Especially if there are a lot of subscribers. There must be a better way to find them that is less resource intensive.
Edit: I left out part of the explanation.
There is a subscribe method too
subscribe("user", cb);
subscribe("user_preferences", cb);
subscribe("user_preferences_food", cb);
These subscriptions are stored in an array in the framework.
As soon as "user_preferences_food" is updated for example, all subscriptions above should be triggered. But obviously not subscribe('othervar');
simplification of the subscribe method:
var subscriptions = [];
function subscribe(var, callback){
subscriptions.push({var: var, cb: callback});
}
Simplification of getVar
vars = {};
getVar(var){
// find var in vars with this logic: https://stackoverflow.com/a/18937118/249710
// current exact match on subscribers, but need the "parents, grandparents etc here
var toUpdate = _.where(subscriptions, {
"var" : var
});
_.each(toUpdate, function(sub){ sub.cb();});
}
Storing or getting data as part of the key I've already got covered. It is just finding the subscribers in the most effective manner
ps: this is in an environment where I cannot rely on ES6 yet (not all users have it enabled), there is no DOM but I do have underscore included. (Titanium app development platform)
I would try to make a list for the callbacks, so you loop trough one list so you dont have to search, because you know the list is there with all the callbacks.
So if you call setVar('user_prefs') you set a seperate list with the root var. in this case its the user.
if any object is changed with setVar (in depth or not) you go to you're root var, get the list and loop trough this list with the callbacks.
The beauty of this is you can set a list with the root var,
var cbList[FIRSTVAR] this contains all the callbacks. No searching just loop.
Its the mongoDb principle, the data is ready to go, you don't search because you know the list is already there.
You could split the string and use it for reduceing the object.
function getVar(object, path) {
return path
.split('_')
.reduce(function (o, k) {
return (o || {})[k];
}, object);
}
function setVar(object, path, value) {
var keys = path.split('_'),
last = keys.pop();
keys.reduce(function (o, k) {
return o[k] = o[k] || {};
}, object)[last] = value;
}
var object = { user: { preferences: { food: "vegetarian" } } };
console.log(getVar(object, "user_preferences_food"));
console.log(getVar(object, "user_preferences"));
setVar(object, "user_preferences_food", "meat");
console.log(object);
setVar(object, "user_preferences", {"food": "meat"});
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I ended up doing this:
var options = [];
var parts = key.split('_');
var string = parts[0];
_.each(parts, function(p, i){
if (i > 0) string += '_' + p;
options.push(string);
});
var toUpdate = _.filter(subscribers, function(sub){
if (sub.var.indexOf(key + '_') === 0) return true;
if (options.indexOf(sub.var) > -1) return true;
return false;
});
So checking with indexOf on the string to see if there are children. And building an array with parents so any layer is a match, and doing an indexOf on that as well. I think this is the least complicated method of implementing it

Using Firebase Push key as Key in Second Push

I'm trying to add two related items to my Firebase database. I want to push one item, then get that item's newly created key and use it as the key for the second item in a different tree. I've tried querying the database to get the last key created and using it as the key for the second push, but it's still just generating a new key for it. Here's the code that I'm using:
save: function() {
if (this.$.document.isNew && (this.editableCard.title || this.editableCard.body)) {
return this.$.document.save(this.cardsPath).then(function() {
this.$.document.reset();
var sceneRef = firebase.database().ref().child(this.cardsPath);
var scene = sceneRef.orderByKey().limitToLast(1);
var sceneKey = scene.key;
this.$.document.save('/documents/', sceneKey);
}.bind(this));
}
return Promise.resolve();
}
(I'm using Polymer, and my starting point is the note-app demo for Polymerfire).
Any ideas on how I can retrieve the new key of the first push and use it for the second push? Thanks!
EDIT
I found the answer in Firebase's documentation for Reading and Writing to the database for Web. Link
push() returns a DatabaseReference immediately. You can ask that reference what its key is, using getKey(), then use that string to update another location in your database.
You can access the key property on the original database reference and use that as the key for the second one, like so:
let firstObjRef = firebase.database().ref('/first/path/).push(firstObj, (error) => {
videoObj["roomUploadedTo"] = this.roomName;
var updateObj = {};
updateObj[videoObjRef.key] = videoObj;
firebase.database().ref('/second/path/').update(updateObj).then( (e) => {
console.log('update went through. booyah! ' + e);
})

Compare Objects in Array and Remove Duplicate & Update - Javascript

I have an array of objects that presents as follows:
0: Object
ConsolidatedItem_catalogId: "080808"
ConsolidatedItem_catalogItem: "undefined"
ConsolidatedItem_cost: "0"
ConsolidatedItem_description: "Test Catalog Item"
ConsolidatedItem_imageFile: "27617647008728.jpg"
ConsolidatedItem_itemNumber: "1234"
ConsolidatedItem_quantity: "1"
ConsolidatedItem_source: "CAT"
ConsolidatedItem_status: "02"
ConsolidatedItem_umCode: "EA"
1: Object
ConsolidatedItem_catalogId: ""
ConsolidatedItem_catalogItem: "undefined"
ConsolidatedItem_cost: "0"
ConsolidatedItem_description: "ALARM,SHUTDOWN SYSTEM,AXIOM,XP3, 0-1500 PSIG, HIGH AND LOW PRES Testing"
ConsolidatedItem_imageFile: ""
ConsolidatedItem_itemNumber: "10008"
ConsolidatedItem_quantity: "1"
ConsolidatedItem_source: "INV"
ConsolidatedItem_status: "02"
ConsolidatedItem_umCode: "EA"
I'm trying to update and remove an object if it's added again, or update the object. Preferably update the object with the new value. My code is as follows:
var result = $.grep(finalObject, function(e) {
return e.ConsolidatedItem_itemNumber == o.ConsolidatedItem_itemNumber;
});
console.log(result);
if (result.length == 0) {
finalObject.push(o);
shoppingCounter = finalObject.length;
$('#numberShoppedItems').text(shoppingCounter);
console.log(finalObject);
} else if (result.length == 1) {
finalObject.filter(function(x){
result = x;
console.log(result);
return x == result.ConsolidatedItem_itemNumber;
});
} else {
alert('Multiples Found');
}
}
I've tried multiple ways of getting the exact object and manipulating the data, however they've all failed. I would prefer to update the object, say if CatalogItem_itemNumber held the same value, if the CatalogItem_quantity was different - add the CatalogItem_quantity values together and update the array of objects.
I don't need an exact answer, a nudge in the right direction would do wonders though. I've looked at several of the related questions over the past couple of hours but none of them seem to address the issue. If you know of a question that has an answer, feel free to just link that as well. I may have missed it.
No Underscore.js please
When you find the matching record, you may update it by using $.extend
$.extend(result[0], o)
This will update the object in finalObject array in-place.
Alternatively, if you want to use the filter, you will need to insert the new object in the array.
finalObject = finalObject.filter(function(x) {
return x !== result[0];
});
finalObject.push(o)
Here we are allowing all the records that are not not equal to result to be returned in the resultant array that is received in finalObject. In next line, we are adding the new record.
Solved in the following manner:
1.) Verify object is not empty.
2.) Use .some() on object to iterate through it.
3.) Check if the finalObject, which is now e, has a match for the key in my temporary object I assemble, o.
4.) Update the values that need updating and return true;
Note: Originally I was going to remove the object by its index and replace it with a new object. This too can work by using .splice() and getting the index of the current object in that array you're in.
Here is the updating version:
if (o.ConsolidatedItem_quantity != '') {
var result = $.grep(finalObject, function(e) {
return e.ConsolidatedItem_itemNumber == o.ConsolidatedItem_itemNumber;
});
if (result.length == 0) {...}
else {
finalObject.some(function (e) {
if(e.ConsolidatedItem_itemNumber == o.ConsolidatedItem_itemNumber){
var a;
a = +e.ConsolidatedItem_quantity + +o.ConsolidatedItem_quantity;
e.ConsolidatedItem_quantity = a.toString();
document.getElementById(o.ConsolidatedItem_itemNumber).value=a;
return true;
};
});
}
}

Categories