Can't access data in array after mapping it from api pull - javascript

So I have pulled some data from an api using a fetch in a React app, then I have used .map to get the data I want into arrays that I am trying to present in a table sort of format.
When I log the mapped arrays it presents the data I am after, but when I try access it to present specific elements of it it's returning undefined.
If the array in the console log shows that it has elements name and age, is there something I am doing wrong to get undefined when I try and access it? Or maybe I am accessing it the wrong way. Any help would be appreciated.
function getMap(results) {
return results.map((res) => {
return {name: res.name, age: res.age}
}
fetch(URL)
.then(result) {
let x = getMap(result.result);
console.log(x);
///// the console log shows an array [{name: 'Peter', age: 30}]
console.log(x.name);
///// console log returns undefined
})

you aren't accessing the array correctly. Remember an array is like a "list" of things, in this case, objects. Each object has two properties, name and age. The way you are trying to access it in your second console.log, you are trying to access a .name property on the array itself. This is pretty basic, but to access an item in an array, you pass an index (starting at zero), like so: myArray[0]. So to access the name property of the first item in your array, you would use x[0].name. To iterate over the entire array, you could do x.forEach(item => console.log(item.name))

Related

How to get a JSON object's key from the object itself in JavaScript/a Vue v-for loop?

I'm not looking for the keys that this object contains but the key of the object itself (the key in the array containing the object).
I have this JSON:
{
"Object name (text)": {
"raw": "Some more text.",
},
"Another name": {
"raw": "Some other text.",
}
}
and would like to get "Object name (text)" for the first item.
My Vue code is:
<CustomComponent
v-for="object in objects"
:key="getKey(object)"
:object="object"
/>
I'm not sure if the getKey-method approach is how one is intended to get unique identifiers for iterating through the JSON array. Its code currently is:
getKey(object) {
return Object.keys(object)[0];
}
Now I'd like to somehow pass the name of the object to the CustomComponent ("Object name (text)" in the first case).
One temporary workaround that I intended to use until I find something more appropriate was getting the keys from the objects array like so:
:objectName="getObjectName(object)" and itemNumber: -1 in data and this method:
getObjectName(object) {
this.itemNumber = this.itemNumber + 1;
var objectName = Object.keys(this.objects)[this.itemNumber];
console.log("Object name: ", objectName);
}
However, the first line of this method causes it to run hundreds of times instead of only two times (why is that?; it works in the first 2 executions of the method and when commenting out that line) and I think this is unlikely the proper method to simply retrieve the object's name/key.
It also didn't work when putting the above code into the getKey method which would make more sense (and I had the code in that method before creating a separate method to debug). Then the key could be accessed in the component with this.$vnode.key However, it keeps being undefined. This might be a separate problem even though it could resolve this problem here as well - I might create a new question for it. It enters the methods "getKey" and "getObjectName" 6 times each even though it only renders two items on the page, like it should.
-> How to get the JSON object's key in JavaScript?
(Preferably from the object itself after iterating through a JSON array with a loop with Vue instead of only indirectly by checking the objects array.)
Edit: as a workaround I have now done this:
var keys = Object.keys(this.objects);
keys.forEach(element => {
this.objectsWithKeys.push({
object: this.objects[element],
key: element
});
});
<CustomComponent
v-for="objectWithKeys in objectsWithKeys"
:key="objectWithKeys.key"
:object="objectWithKeys.object"
>
</CustomComponent>
this.$vnode.key
This is solved, I used var objectsWithKeys = data[Object.keys(data)]; and {{ $vnode.key }}.

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 string/object/array confusion with JSON

I'm having a Laravel backend return some errors via Validator. These errors are passed through a HTTP response made by angular, and returned in JSON format.
The object is structured as seen below:
That name object has a value, which is the actual message that I'm after.
Currently, using loops etc., I can only get the name of the array (name) as a string...
I sometimes get multiple arrays within this error object, and I won't always know their names, so how may I retrieve that 0-index value in each of them, in a loop?
Thanks for any help.
Edit #1
Looping through it like this:
for(var err in res.data.errors){
console.log(Object.err[0][0]);
}
Gives me a Cannot get [0] index of undefined
How about this:
let errors = Object.values(response.data.errors);
// errors is now an array of arrays containing the validation errors
errors.forEach( (errorArray) => {
console.log(errorArray[0]);
} );
Another approach would be using Object.keys() instead of values. This is similar to what you already tried, where you get the name of the error property as a string, and then use it to access each error array:
let keys = Object.keys(response.data.errors);
keys.forEach( (errorKey) => {
console.log('error type', errorKey);
let errorArray = response.data.errors[errorKey];
console.log(errorArray[0]);
} );

How To Efficiently Extract Certain Information From A POJO

I am working a lot with firebase, and am trying to load certain information from the database. The original data comes from a query, and is returned to me in a POJO. The console prints this when the original data is returned:
-KhQ76OEK_848CkIFhAq: "-JhQ76OEK_848CkIFhAq"
-OhQ76OEK_848CkIFhAq: "-LhQ76OEK_848CkIFhAq"
What I need to do is grab each of the values (-JhQ76OEK_848CkIFhAq and -LhQ76OEK_848CkIFhAq) separately, and query the real-time database again for each one. I can manage that aspect, but I cannot seem to figure out how to separate the values.
I have already tried to get a single output by doing:
console.log(vals[0]) but it just returned undefined, and splitting the string by " would be very inefficient for large data sets. Any ideas?
To access the values, you can iterate the snapshot's children using the snapshot's forEach method. The keys and values of the children can be obtained using the key property and the val() method:
firebase.database()
.ref("some/path")
.once("value")
.then((snapshot) => {
snapshot.forEach((childSnapshot) => {
console.log(childSnapshot.key); // The child's key: e.g. "-KhQ76OEK_848CkIFhAq"
console.log(childSnapshot.val()); // The child's value: e.g. "-JhQ76OEK_848CkIFhAq"
});
});
To solve this issue, all I did was convert the object returned into an array by using this code below:
var Array = Object.keys(datalist).map(function(k) { return datalist[k] });
Works like a charm, and I can now run a simple for loop for Array

issues accessing an array in an object jquery

I am trying to access some data from an object as follows:
var summaryChanges = {
dataToAdd:[
{name:[]},
{events:[]},
{emails:[]}
],
dataToRemove:[
{name:[]},
{events:[]},
{emails:[]}
]
}
i am trying to log the contents of the name property of data to add as follows:
console.log($(summaryChanges.dataToAdd.name)[0]);
however the console only logs undefined.
dataToAdd is an arrary not an object , so access it like
console.log(summaryChanges.dataToAdd[0].name[0])
You need to realize some things
$(summaryChanges.dataToAdd.name) you are creating a jQuery Object.
summaryChanges it's an object so you can do sumaryChanges.dataToAdd
dataToAdd it's an array, so for get a value you access it like this dataToAdd[index]
At the end you access it like this
console.log(summaryChanges.dataToAdd[index].name[index])

Categories

Resources