This is the code I use:
localStorage["FSS"] += JSON.stringify(favSongs);
localStorage["FSTS"] += JSON.stringify(favSongTitle);
localStorage["FIS"] += JSON.stringify(favImages);
But when I retrieve the values I get this:
For FSS: undefined["0t0FGyhB6C8"]
For FSTS: undefined["SONIC SYNDICATE - Denied (OFFICIAL MUSIC VIDEO)"]
For FIS: undefined["https://i.ytimg.com/vi/0t0FGyhB6C8/mqdefault.jpg"]
I don’t understand how and where the undefined comes from and how I remove it to log the results on my screen (now when I log it it says undefined as well).
The undefined is what was already in localStorage:
document.getElementById('existing').textContent = localStorage[Math.random().toString()];
Because you use the foo += bar syntax, the script will:
Get the existing value of foo
Perform type coercion to make foo and bar compatible
Append bar to the existing value
Assign the combined value back to foo
If foo already contains undefined...
This appears to be an artifact of accessing the localStorage properties via the map accessor. If you used the getItem method, you would receive null instead of undefined.
Since you're working with JSON, the simple string concatenation (string +=) won't work even if you already have a value. You would end up with ['foo-album']['bar-album'], which is not valid. I would recommend getting the existing item or an empty array, appending your new item, then replacing the stored value:
var prev = localStorage.getItem('FSS') || '[]'; // get the existing value or the string representing an empty array
var data = JSON.parse(prev); // parse into an object
data.push('New Album');
localStorage.setItem('FSS', JSON.stringify(data)); // convert back to JSON and set
Related
I'm lost on how to get object properties in JS. I'm getting values from firebase and I wanted to filter the result by its id:
//id is from query params (selecting 1 item from view)
const snippet = snippets.filter(snips => {
if(snips.id == id) return snips;
})
If I console.log after these lines, I'm getting this:
const obj = snippet[0];
So I tried to get properties by using snippet[0] which returns this:
But if I try to get properties such as:
console.log(obj['id']);
//console.log(obj.title); - tried this as well
it returns:
Entering data:
This isn't how the array::filter function works. It iterates over the array and the callback returns a boolean true/false if the element should be returned in the result array.
const snippet = snippets.filter(snips => snips.id == id)
Issue
Cannot read property "title" of undefined
This is saying that snippet[0] is currently undefined when trying to access any properties
snippet[0].title, a root title property also doesn't exist in your other console log
Solution
Your snippet is (possibly) an array of 1 (or 0) element, so in order to access the title nested in data property
snippet[0].data.title
And in the case that the array is empty or has an element without a data property, use optional chaining or guard clauses to check the access
snippet[0]?.data?.title
or
snippet[0] && snippet[0].data && snippet[0].data.title
looking at what you are asking you need to enter first the data.
console.log(obj[0].data.content)
i know this is kind of weird question but, i was creating a guard to prevent duplicate values in array i write some part and got a little help from stackoverflow but i can't understand code meaning properly
so i created Object with null prototype and iterated for loop over it to detect duplicate values (i know Set constructor is much easier but i am doing it in my server-side code and since older browsers does not support Set it would be dangerous to use Set). here is my code
var duplicateTagsGuard = Object.create(null);
for(var co = 0; co < tags.length; co++){
let val = tags[co];
if(val in duplicateTagsGuard){
return res.status(409).send({
message: ''
})
}
duplicateTagsGuard[val] = true
}
and the part i cant understand is duplicateTagsGuard[val] = true
so if we split my code step by step and explain it would be like
1.first create null Object
2.iterate for loop on it and declare variable val and make it equal to every element in tags array
3.then check if that val is in duplicateTagsGuard object and if it is use return statement to prevent continuing for loop and if it is not then we are adding val's value to object but i don't know how it is implemented with that part of code (duplicateTagsGuard[val] = true) if anyone can explain i will be glad
first create null Object
It is not creating a null object but it is creating an object with null as the prototype check the Object.create docs:
var duplicateTagsGuard = Object.create(null);
console.log(`duplicateTagsGuard is an empty object:`);
console.log(duplicateTagsGuard);
console.log(`Prototye of duplicateTagsGuard is null: `);
console.log(Object.getPrototypeOf(duplicateTagsGuard));
iterate for loop on it and declare variable val and make it equal to every element in tags array
This part is correct every time the loop runs a new variable is created with for block scope and is assigned the value of the current coth index value of the tags array.
then check if that val is in duplicateTagsGuard object and if it is use return statement to prevent continuing for loop and if it is not then we are adding val's value to object but i don't know how it is implemented with that part of code (duplicateTagsGuard[val] = true)
It is checking whether val is a property of the duplicateTagsGuard object, if it is already present then the return is used to return the response else it is adding that property to the duplicateTagsGuard object with the bracket notation [propertyName] and assigning it's value as true.
var duplicateTagsGuard = Object.create(null); //creating a new empty object with prototype as null
let val = "hello"; //creating a new variable
duplicateTagsGuard[val] = true; //adding the property with the value of the variable val
console.log(val in duplicateTagsGuard); //checking if the added property is present in the object
The code is creating a dictionary of val. Basically, when you iterate through the tags array, it checks whether the item in the array (accessed by tags[co]) is already present in the dictionary duplicateTagsGuard. If it has been encountered before, it will perform a certain action.
At the end of the loop, it simply injects the item into the dictionary. The dictionary therefore keep track of whether an item has been encountered before in the for loop.
The injection is done by using the item as the key in the dictionary, since it is easier to look it up (you simply have to do item in dictionary, which is basically val in duplicateTagsGuard in the actual implementation of the code). It does not matter what value you use, so a true value is used as a placeholder.
I'm using cts.uris in my search query. I'm assigning it to a variable like:
var x = cts.uris(...);
What is the output type of x?
I'm using JSON documents in my application and want to use xdmp.nodeReplace on some 2 objects. I'm performing an update on my document after checking the value of "x" to be valid or not after writing a search query inside cts.uris.
if(x.toString().length>0)
//x is cts.uris output. Checking if it gets a value then do the update like this.
{
var newObject = x;
newObject.field1="new value";
//field 1 value updated in the clone of original file
newObject.field2="new value"; //same as above
return xdmp.nodeReplace(x, newobj);
}
I expect the newObject to have all the contents of the origial file that we fetch and put in "x" and then update the values as given in the above code.
Once it is updated then it should replace the original document with the new values.
I'm currently getting an error like: "XDMP-ARGTYPE: xdmp.nodeReplace"
cts.uris returns a Sequence of uris. You probably want to iterate over the Sequence using a JavaScript for..of construct. An example is given in above link.
Note though that a uri is not a full document, but just its identifier. It doesn't make sense to assign values to it like that.
To make updates to documents inside MarkLogic, either reinsert the document, or read it using cts.doc, isolate the property you want to update, and nodeReplace it as you intended.
HTH!
So the problem, i have data that i call by using window.blah.blah and it will spit out info based on a user or an item in a database.
Now my problem is that i want to use the window.blah.blah with a dynamic appendage so like window.blah.blah.VARIABLE1
i have tried window.blah.blah.instances[variable] but i get a typeerror saying the value of variable is not defined (so if variable = test1 the error would be TypeError: Cannot read property 'test1' of undefined. variable is generated so it can be test1 test2 that correspond to stored objects.
if it helps i am using the call within a loop that is using it to get access a stored json obj with different object names.
also if I one of the objects is called test1 and i do window.blah.blah.test1 it accesses the object but window.blah.blah.instances[test1] gets the above error.
What am i doing wrong?
Perhaps the syntax you are looking for is window.blah.blah[VARIABLE1]
(assuming the blahs are objects.)
note that storing data on window is typically a bad idea, so for the following example, I'll move the top-level object from the global space (accessed through window) into a local variable:
var myObj = {
blah: {
blah: {}
}
};
var fooVar == 'foo';
function getMyDynamicVariable() {
return "foo"; //really this would by some dynamically generated string
}
//example usage:
myObj.blah.blah[getMyDynamicVariable()];
// OR
myObj.blah.blah[fooVar];
// would be the same as
myObj.blah.blah.foo //(in this exact example, where all functions and variables contain the string 'foo'.)
i am trying to get a value from a key stored on a string variable proyNombre, but whenever i call it via the common method "myAssociativeArray.MyKey", it gets the variable 'proyNombre' as the key, instead of getting its value and passing it as a key.
proyectos.each(function(index){
var proyNombre = this.value;
if(!(proyNombre in myArray)){ // whenever the variable is undefined, define it
myArray[proyNombre] = horas[index].value-0 + minutos[index].value/60;
}
else{
console.log(myArray.proyNombre); //This doesnt work, it tries to give me the value for the key 'proyNombre' instead of looking for the proyNombre variable
console.log(myArray.this.value); //doesnt work either
}
});
Try:
console.log(myArray[proyNombre]);
myArray is actually an object in javascript. You can access object properties with object.propertyName or, object['propertyName']. If your variable proyNombre contained the name of a property (which it does) you can use the second form, like I did above. object.proyNombre is invalid - proyNombre is a variable. You can't do for example:
var myObject = {};
myObject.test = 'test string';
var s = 'test';
console.log(myObject.s); // wrong!!
but you could then do:
console.log(myObject.test);
console.log(myObject['test']);
console.log(myObject[s]);
You need to use the same syntax you used to set the value:
console.log(myArray[proyNombre]);
Simply access the value with myArray[proyNombre].
You're doing it right in the assignment: myArray[proyNombre]. You can use the same method to retrieve the variable.
If you change:
console.log(myArray.proyNombre);
console.log(myArray.this.value);
to
console.log(myArray[proyNombre]);
console.log(myArray[this.value]);
You should get the same value (the value for the key represented by the variable proyNombre) logged twice.
It's true that Javascript doesn't have associative arrays but objects in Javascript can be treated like associative arrays when accessing their members.