I have an array called this.state.arr, which I added values to in another function in my app.js file. In the render() function I console.log(this.state.arr) the array to show and it shows like this:
[]
0: "a"
1: "b"
2: "c"
length: 3
However, I want to be able to access the individual elements of each array. I've tried this.state.arr[0], or const list = this.state.arr.map((e) => {return e;}); I've also tried some other commands to access the insides of the this.state.arr array.
But none of those worked. I just kept getting null in the console when I tried to access the inner elements of the array. Any help would be greatly appreciated!
Having null get returned for your attempts to access items in this.state.arr is pretty unusual and makes me think that something else is populating or interfering with your array. When you try to access an item at an index your array that doesn't have a value undefined will get returned. null is typically used to indicate a value/property/attribute is intentionally being set to blank.
I'd double check where you are setting / accessing the arr. Posting that part of the code may help.
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 was shocked that the result of
document.writeln(Object.keys([,1,,1]));
is
1,3
which filters the index of an array that doesn't contains anything automatically. But when I try to print out Object.keys([,1,undefined,1]):
document.writeln(Object.keys([,1,undefined,1]));
the result is:
1,2,3
which is different from the previous one, and I try to print the value of index 2 at the first one:
document.writeln([,1,,1][2]);
which is undefined actually. Why would Object.keys([,1,,1]) and Object.keys([,1,undefined,1]) return different results?
In Object.keys([, 1, undefined, 1]) case, you are explicitly defining the third element to be undefined, but in Object.keys([, 1, , 1]), there is no element associated with the index 2. So, 2 is recognized as an array index in the first case, but not in the second case.
Just to represent the holes in the array, when you actually reference it, undefined is returned. That is why [, 1, , 1][2] is undefined.
This is one caveat to be careful with Javascript arrays : you can have sparse arrays, arrays with missing values, which is not the same as having undefined values (the array element exists, like a variable can be declared, but it's value is `undefined).
Note that you can get the same behavior using delete on an array element.
As already said, you can test for empty value wiht === undefined, which is even more confusing, because it does not usually cause the same output.
You're right to think that it doesn't make much sense. It doesn't. Basically, in javascript there is sometimes a difference between "undefined" and "has never been defined". In the first example, you're not giving the second index any value, so it doesn't print. In the second example, you're giving it a value (even though that value is undefined, it's still getting a value) so it prints it.
I understand that when index names are used to push values in Javascript, they essentially work like objects. But what I don't understand is the following behaviour -
person = [];
person[0] = "Someone";
person["test"] = "SomeoneElse"
Inputting person on the console prints ["Someone"] and I could see no information about person.test.
person.test does print SomeoneElse. However, if I go console.log(person), I get ["Someone", test: "SomeoneElse"].
Curious to check if this makes sense, I tried to create a structure like this one -
var experiment = ["Someone1", test1: "SomeoneElse1"]
and what I get is
Uncaught SyntaxError: Unexpected token
What am I missing?
Thanks in advance!
Typing person on the console prints ["Someone"].
Array.prototype.toString formats this output, and it only considers the "array values" of itself without other properties.
However, if I go console.log(person), I get ["Someone", test: "SomeoneElse"].
console.log outputs other information about the object, including own properties.
Uncaught SyntaxError: Unexpected token
Because that is bogus syntax; the array literal syntax doesn't allow keys, because array values aren't supposed to have keys. Arrays are a numerically indexed list of values. Merely by the fact that under the hood those lists are implemented using objects (because everything in Javascript is an object of some kind or another) are you able to set "non numeric keys" on the array. That doesn't mean you're using the array correctly though.
Also see Are JavaScript Array elements nothing more than Array object properties?
This is because an array in JavaScript is also an object itself, and objects can have properties. So it is perfectly valid to have an array with elements, but also have properties set on the array object.
The second example doesn't work because the [...,...,...] syntax is specifically for instantiating an array and its elements.
typing person in console is like having an alert(person); or passing its value to a variable or element, so it is more like you want to get the first set of readable values. That is the reason why it is showing you the values inside, you can try adding person[1] = *something;*, then it will display someone, something
console.log(person) - it displays all the items inside an object. It is more like informing you of what is inside, like a text visualizer in your IDE
var experiment = ["Someone1", test1: "SomeoneElse1"] - it will absolutely throw an exception there is no such format like this on initializing values, at least it is expecting an array format like var experiment = ["Someone1", "SomeoneElse1"]
I'm trying to use the Underscore.js libarary's findWhere function to efficiently find an object from an array on a node.js server and I can't understand why it always returns undefined.
I tested the function using the node console and the object definetely contains an object with the specified key yet still nothing is returned when using findWhere.
Here I ensure that the value for the 'fixture' key I am looking for in findWhere does indeed equal the matching value in the object I was hoping to have returned:
'55785f4e38bd12511018145d' == predictions[0].fixture;
true
When checking what values were held in the array being searched by findWhere I confirm that the value does exist:
predictions
[ { fixture: '55785f4e38bd12511018145d' } ]
Checking the value I hope to have returned:
predictions[0].fixture
'55785f4e38bd12511018145d'
Running the findWhere query which returned undefined:
var foundPrediction = underscore.findWhere(predictions, {fixture: '55785f4e38bd12511018145d'});
undefined
The only reasons I can think of are that this has something perhaps to do with casting or maybe a '===' that returns false within the function, but is there any way I can get findWhere to return the object as desired, or will I have to resort to a manual search using a for loop?
Thanks in advance!
There is nothing wrong in your code. Looks like you're running in console, thats why after hitting enter , console is showing undefined. You perhaps thought that foundPrediction value is undefined. You need to console the foundPrediction variable to get the required result.
Also there is nothing wrong with casting as it returns true.
var predictions = [{
fixture:'55785f4e38bd12511018145d'
}]
console.log('55785f4e38bd12511018145d' === predictions[0].fixture);
var foundPrediction = _.findWhere(predictions, {fixture: '55785f4e38bd12511018145d'});
console.log(foundPrediction);
I have added the code in jsFiddle. Hope it helps
This is probably really simple but I have a statement...
console.log($scope.data);
And in the console window I see...
[pension: "123", postcode: "GL"]
I have two questions...
What type of object is this?
How do I get access to the value (rather than the key) with a for
loop?
I tried...
for (item in $scope.data) {
console.log(item[1]);
}
But all I get is...
e
o
Not I cannot use the 'pension' or 'postcode' I need to be able to iterate the collection.
I was thinking I would need to use JSON.parse? But this seems like an overkill, because I originally instantiated $scope.data as an array. So why cant I access it like an array?
That's just how for..in loops work. The keys are assigned to item one by one, and then you use $scope.data[item] to get the value of that particular key.