From array of objects, extract value at certain index --> undefined - javascript

I have a problem in getting a value from a certain index form an array of objects.
The Array looks something like that:
[Object, Object, Object, Object]
When I open them in the Crome console, it looks like this:
The thing is that I want the value of uuid from one of this Objects.
If I write console.log(this.myArray[0].uuid) I am getting the uuid from index 0.
But as soon as I write console.log(this.myArray[index].uuid), where index is a number, I only get undefined.
I already tried
var test = _.map(this.myArray,"uuid");
console.log(test[index].uuid)
but that only get's me undefined
Can someone please help me?

if you want index loop array like this
for(var i = 0;i<this.myArray.length;i++){
console.log(this.myArray[i].uuid)
}

I think you're mistaken on how _.map works when passing a key:
let arr = [
{ index: 4, name: 'Hello' },
{ index: 9, name: 'World' }
]
_.map(arr, 'index') // produces [4, 9]
As a result, if you wish to access the index value, you would do so directly from the array itself.
let indexes = _.map(arr, 'index')
indexes[0] // 4

I have already tried
var test = _.map(this.mycards,"uuid");
console.log(test);
console.log(test[index]);
the fist console.log
console.log(test);
results in an Array with all the uuid's:
["3c539a73-d569-4512-b558-291164f34529", "b6920edc-77a8-4ac6-8fa3-65c7b05ea556", "9d8afb0c-5268-44a1-b02f-0772357025d0", "4a33b232-7c1d-4ee7-b53c-3615c0fbd7d3", "68888839-a888-4595-9be9-3ec07fe35850", "0ab242ca-e6e1-4497-871e-196c3a05e0ec", "0c311bc6-c396-45a9-865e-19cdc8800bf7", "3add00ad-7371-417a-89ae-e4f0966ab503", "ac503849-5476-4710-9c2e-a514a178c4f5"]
but with console.log(test[index]); I get again undefined as a result.
The thing is, that my method looks something like that:
event(index, eventObject) {
...
};
and index is always a number, which I don't know, because it differs every time the method is called.
But for some reason when I put in a number instead of index (which is also a number) like this this.myArray[0].uuid I get the a result.
But when I change to this.myArray[index].uuid I get undefined.
I even tried parseInt(index) but that also didn't work.

Related

Accessing directly to a sub array of object it becomes an object of objetcs

I need an array of objects to be passed to cavansJs. This array is an element of a more complex object passed from PHP to a JS script in this way
var active_alarms_data = JSON.parse('<?php echo json_encode($activePriceAlarms,JSON_NUMERIC_CHECK);?>');
I tried also
var active_alarms_data = <?php echo json_encode($activePriceAlarms,JSON_NUMERIC_CHECK);?>;
This is the structure of the main object
The data for the chart is in the sub-array factory_made_avg_graph_prices_stats, printing on console.log the whole object, this field appears to be properly formatted as an array; it can be seen that is declared as an Array type with 104 elements each of which is indexed with a number from 0 to 103. Good is what I need!! But, when I refer directly to the array I got something of very strange
console.log("ELEMENT 0: " + active_alarms_data[i].graph.factory_made_avg_graph_prices_stats);
I got
and the chart remains empty probably just because the expected data format is different than the past one. Any suggestion?
Nothing is wrong with your code.
It's just the console log that is throwing you off. Accessing each of the elements as you are now will work fine. The reason you are seeing [object Object] is because when you concatenate (join with '+') something to a string in javascript, if it isn't a string, it will try to convert it to a string first.
You are looking at a string representation of each object in the array. If you remove the "ELEMENT 0:" and only log the array, then you'll see what you saw first. here's an example:
const obj = { test: [{ foo: 'bar' }] }
console.log('ELEMENT 0: ' + obj.test)
console.log(obj.test)
Or, if you really needed to see "Element 0", you can use a comma, rather than direct concatenation:
const obj = { test: [{ foo: 'bar' }] }
console.log('ELEMENT 0:', obj.test)
Console like this :
console.log("ELEMENT 0: " ,
active_alarms_data[i].graph.factory_made_avg_graph_prices_stats);
Replace '+' to ',' in console

Getting empty snapshot when reading Firebase Database in Javascript?

I have the following database structure:
I am trying to get the list of values under registrationTokens to then execute an FCM notification to the list of tokens. But the output to the console is empty even though there is a token under the child node. Am I missing something here?
Console output:
registrationTokens [ '0' ]
Part of my JS function code below:
return admin.database().ref('/fcmtokens/' + toId + '/registrationTokens').once('value').then((userTok) => {
const registrationTokens = Object.keys(userTok.val());
console.log('registrationTokens', registrationTokens);
});
Your console output is exactly as I'd expect. You've read the following children from the database:
0: 'c4P...'
Then you asked for the keys of that object to be printed, as returned by Object.keys(). Note that this key a key/value pair: the key is 0 and the value is 'c4P...'. This means that the following call:
Object.keys(userTok.val());
Is going to return an array of keys of the children. Since there is one child with a key of 0, you get this array:
[ '0' ]
So, I'd say your function is working exactly as you coded it. If you want the token values instead, try this:
If you want to tokens for each key instead, maybe you should use Object.values() instead:
Object.values(userTok.val());
I'd expect that to return an array of all the values associated with they keys.

Javascript pushing Array to Array but concatenating instead

I'm trying to push an array (multiple times) into another array. Instead of an array of arrays, I'm getting all the values from the multiple push attempts as a single array. I've tried pushing an array implicitly (i.e. push([val1,val2]), explicitly creating a new Array, then pushing the new Array. Here's the key part of the code:
var coordinates=[];
...
for(i=0;i<6;i++)
{
...
for(var j=start;j<circum[i].length;j++)
{
var segmentCoords=[];
...
if(segmentFlag===false)
{
segmentCoords.push([i+1,segmentLength]);
segmentFlag=true;
}
...
if(segmentFlag===true)
{
var tempArray=new Array(i+1,segmentLength);
segmentCoords.push(tempArray);
segmentLength+=sectorLength;
coordinates.push(segmentCoords);
segmentFlag===false;
}
...
}
From the many stackoverflow questions/answers I've looked at, I expect my coordinates array to look something like this: [[val1, val2],[val3,val4],[val5,val6]]. Instead it's [val1,val2,val3,val4,val5,val6]. That is what I would expect if I were using .concat() or .apply().
Can anyone explain why my code isn't generating an array of arrays?
I've got the full code here https://jsfiddle.net/Seytom/7xm9s4qr/ in case you want to see more of it.
You seem to be fooled by your console.log. Notice the difference between these two statements:
console.log( 'string ' + [[1,2],[3,4]] ); // string, '1,2,3,4'
console.log( 'string ', [[1,2],[3,4]] ); // string, [[1,2],[3,4]]
Because you are coercing the array into a string, this is the result. Its the same as:
console.log( new Array([1,2],[3,4]).join(',') ); // 1,2,3,4
It's simply what arrays do when you join them, regardless of whether they are nested. It is better to log the array separately so you can explore it in your console, so simple print your string and then add the array as the second argument. (The console takes an infinite amount of arguments and will print them all as one statement - safari even prints the first as a special type if its a string so its clearer to read).
In short: push behaves exactly as expected, and your code should simply work as intended, but the printing to the console seems to leave a bit to be desired :).
Use Array.concat:
var arrA = [0];
var arrB = [1, 2];
while (arrA.length < 10) {
arrA = arrA.concat(arrB)
}
console.log(arrA)

delete array[x] deleting value but not the whole element

I have an object which has duplicate values so i used delete new_object[1] to delete the value but when I see this in console its showing undefined in object 0800
["293", undefined, "298", "297"]
You should use
arr.splice(index, 1);
delete only removes the element, but keeps the indexes. This question is similar in nature and provides more information.
I think you should use splice
a = ["1","2","3"];
a.splice(1,0)
console.log(a) //["1","3"]
var test = [1,2,3,4];
delete test[1];
now if you print the test variable, you will get
=> [ 1, , 3, 4 ]
that is why you have got undefined
like everyone here is answering, you should use splice
test.splice(1,1);
and now print the test variable will give you
=> [ 1, 3, 4, 5 ]
you need to use splice() in order to remove the value from the array. What you are doing is simply setting it to undefined.
var myArray = ['295', '296', '297', '298'];
// removes 1 element from index 2
var removed = myArray.splice(2, 1);
// myArray is ['295', '296', '298'];
// removed is ['297']
Reference from Array.splice
The splice() method changes the content of an array by removing
existing elements and/or adding new elements.

Array containing objects has wrong length

I have an array like:
errors = [ {...}, {...}, {...} ]
It's an instanceof array, yet it only returns 1 for .length?
Relevant code:
if(data.error){
errors.push({'element':ele,error:data.error});
}
//Above is looped a few times and there are N number of errors now inside
console.log(errors) //Returns 2+ objects like {...}, {...}
console.log(errors.length) //Returns 1
For Uzi and Muirbot, here's the errors array:
[
Object
element: b.fn.b.init[1]
error: "You must enter "example" into the field to pass"
__proto__: Object
,
Object
element: b.fn.b.init[1]
error: "Crap!"
__proto__: Object
It is correct, this code:
var errors = new Array();
errors.push({'element':'ele', error:'data.error'});
...adds ONE object to the array. The object has two properties.
It's possible your code is executing in an order other than what you're expecting. ie, when you log both errors and errors.length, errors does contain only 1 object. But after that you are adding to the errors array, and only after that are you looking at the console. At that point you could see a larger array in errors for two reasons - first, your actual code isn't logging errors but some object that contains errors. In that case the console display is live, and will show you not what was in errors at the time, but what is in it now. Alternatively, the console could just be taking some time to log errors.
Without more code I can't be sure if this is the case. But you could verify it by replacing console.log(errors); with console.log(errors[1]);. If errors is really only 1 long at the time, it will log undefined.
The problem was that Chrome's Web Inspector's console.log is an async event. So, the length was a property lookup so it gave that back instantly, but the object with two items inside was held off until the rest of the events had fired.
In the future I, and others with this issue, should use debugger; instead.
is it an Array object or something that resembles it?
arrays do work:
> a = [{a:1}, {b:2}]
[Object, Object]
> a.length
2
you'll have to provide more code.
and now that you've provided the relevant code, the correct answer is what Steve Wellens said (which was downvoted, by the way).
Array.push adds a single element, objects may have more than one key but they're still a single object so your real case was different from your original example, which of course works.
another possibility:
> a = []
[]
> a.length = 2
2
> a
[]
> a.length
2
> a instanceof Array
true

Categories

Resources