Can't get data from fetched array - javascript

have a mongo database which holds a short list of events with some extra data. The data is returned and sent to the App. This all goes swimmingly. Inside the App I want to extract titles foreach array element, but when i try use or foreach loop the output is undefinded.
** data i get from api:**
{status: 'ok', evnets: Array(1)} evnets: Array(1) 0 {title: 'r', descryption: 'asd', StartDate: '2022-12-16 13:51', EndDate: '2022-12-29 09:52', _id: '63944787606e1280f2e14cde'}
I tried:
foreach()
data.events.forEach(element => {
Title = data.events.title
});

I think the returned data from the API is evnets not events

Related

Iterate over JSON data in JavaScript

I am working on some trains' open data feed and getting some JSON as a response from a server. I parse this JSON into a data variable and display it as seen below. However, I cannot find a way to iterate over the response to be able to manipulate each message. I want to iterate over each message and then use the data for a record in a SQL database. I cannot get to the point of accessing any individual message data.
How can I create a loop to iterate over each message and extract it's data?
[
{
SF_MSG: {
time: '1666370311000',
area_id: 'TD',
address: '0C',
msg_type: 'SF',
data: '1F'
}
},
{
CA_MSG: {
to: '4333',
time: '1666370311000',
area_id: 'WO',
msg_type: 'CA',
from: '4331',
descr: '2K60'
}
}, ...
]
Edit: using data.forEach(function(message) produces an output of the structure:
{ CA_MSG: { to: '6021', time: '1666372120000', area_id: 'CY', msg_type: 'CA', from: 'STIN', descr: '2Y73' } }
, however, how do I query this inner object, the names of the objects will differ depending on message type if this matters?
try this:
data = JSON.parse(yourJSONdata)
data.map((o, i)=>{
//o is the object, i is the index
// do your processing here
then at the end do
data[i]=processedobject
})

Axios sends an array of strings instead of an array of objects

Axios sends an array of strings instead of an array of objects. I have an array of objects that contains data about the event. I'm trying to send a request to the server via axios, but I get a array of strings insteenter image description heread of objects at the output
let data = {
title: 'Game',
subject: 'Some subject',
date: ['01/01/2021','01/01/2021'],
years: ['1970', '1970'],
address: 'None',
ages: [
{
title: 'Men',
weights: [{page: 0, title: '60'}]
}
]
};
api.Create({
params: data
}).then(function (response) {
console.log(response.data);
})
.catch(function (err) {
console.log(err);
});
api response
try to:
console.log(JSON.parse(response.data))
What you get back from the server is string. you need to parse it.
When you send data to and from a server, it is sent as a 'serialized' string, usually JSON format
That's how server responses work
It turned out to be an incorrect request. I used GET to pass the object, instead of POST, so it converts it to a string. I want to notice that there is an evil community on this site.

How do I retrieve firebase child data without also retrieving the key?

I'm currently trying to get the child data without the key in an array so I can add that to my redux state.
ref.orderByChild(`userId`).equalTo(googleUserInfo[0].userId).once('value', streamSnapshot => {
if (streamSnapshot.exists()) {
googleUserInfo[0] = (streamSnapshot.val())
}
Currently this returns
[{…}]0: {-LbJneodI2SaUglB6fwx: {…}}length: 1__proto__: Array(0)
But I would like this
[{…}]
0:
{
displayName: "Seth Jones"
userAvi: "https://lh6.googleusercontent.com/-RABcz3kK1ew/AAAAAAAAAAI/AAAAAAAAAAA/ACHi3rfzHCLV9A7LfiGWKtTOuq5rJmtQpg/s96-c/photo.jpg"
userEmail: "xxxx#gmail.com"
userFirstName: "Seth"
userId: "103977654052015523435"
userLastName: "Jones"
}
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
You need to loop over the results, to get to the individual values:
ref.orderByChild('userId').equalTo(googleUserInfo[0].userId).once('value', streamSnapshot => {
streamSnapshot.forEach((child) => {
googleUserInfo[0] = (child.val())
});

Fetch single array from multiple

I am making angular application where i am making a forEach function with service inside like,
this.data.forEach(function(element) => {
this.appService.getRest(element.optionsUrl, localStorage.getItem('token')).subscribe(result => {
element.options = result.data;
this.getIntake(this.data);
});
});
here i am trying to store the result comes from service to the element.options and then i am calling a function to get back the data value filled with element.options because from the service only i will get the value for options so after that i need to send this data to a function and need to retrieve it..
result.data is an array and it gives the following, [{"id":1,"name":"option1"}],[{"id":2,"name":"option2"}],[{"id":3,"name":"option3"}] respectively for three..
In this.getIntake(data); function if i console.log(data)
getIntake(data) {
console.log(data);
}
then it is giving same array multiple times with same values like..
[
{"name":"abc", value: "abc", optionUrl: "abcUrl", options: [{"id":1,"name":"option1"}]},
{"name":"def", value: "def", optionUrl: "defUrl", options: [{"id":2,"name":"option2"}]},
{"name":"ghi", value: "ghi", optionUrl: "ghiUrl", options: [{"id":3,"name":"option3"}]}
]
[
{"name":"abc", value: "abc", optionUrl: "abcUrl", options: [{"id":1,"name":"option1"}]},
{"name":"def", value: "def", optionUrl: "defUrl", options: [{"id":2,"name":"option2"}]},
{"name":"ghi", value: "ghi", optionUrl: "ghiUrl", options: [{"id":3,"name":"option3"}]}
]
[
{"name":"abc", value: "abc", optionUrl: "abcUrl", options: [{"id":1,"name":"option1"}]},
{"name":"def", value: "def", optionUrl: "defUrl", options: [{"id":2,"name":"option2"}]},
{"name":"ghi", value: "ghi", optionUrl: "ghiUrl", options: [{"id":3,"name":"option3"}]}
]
As the data has three objects, it was reflected three times..
For each object has element.optionsUrl and i need to subscribe that and need to store the data in element.options and if i came out of the service i am not getting the value in options and so i am making a function inside service and passing this.data with options to it.. In that function i am getting the data with values but i need to get completely filled data only once but it gives three as the data has three objects.. From that how to get the final only one array with filled data instead of three.
Stackblitz https://stackblitz.com/edit/angular-kwvjqu
As the service is delayed i am making the function call on run time of the service and sending the data..
How to get only one array from this multiple generated array using pure angular/typescript, javascript way??
Since you are firing the request inside the forEach for each element in your array, it will subscribe for that many times, hence you see it logs 3 times.
RxJS to help.
Instead of loop through your Array with forEach use from, it converts your Array into an array of Observable and you can then do things with it, like fire a http request.
from(this.data) //Converts your data array to array of Observables
.pipe(
mergeMap(element => {
return this.appService.getRest(element.optionsUrl, localStorage.getItem('token')) //fires http request for each element
.pipe(
map((result) => { //change the data
element.options = result.data;
return of(element); //returns an observable for each element
})
)
}),
combineAll() //combines all the observable into one
)
.subscribe(x=>{
this.getIntake(x); //x contains an array of your element
});

How to assign tags for Tag Handler by ioncache from the database

I'm using this plugin called TagHandler. Link: http://ioncache.github.io/Tag-Handler/
May I know how can I assign tags from the database and not hard code to jquery? Example, to assign tags is
$("#array_tag_handler").tagHandler({
assignedTags: [ 'C', 'Perl', 'PHP' ],
availableTags: [ 'C', 'C++', 'C#', 'Java', 'Perl', 'PHP', 'Python' ],
autocomplete: true
});
But I want it from mysql database.
They only gave example for available tags which is using the getData buildin function
$("#ajaxget_tag_handler").tagHandler({
getData: { id: 'user123', type: 'user' },
getURL: '/ajaxtest/get',
autocomplete: true
});
I need the php example. I don't know how to retrieve data in JSON format.
From the website..."By supplying a "getURL" for the tags to be retrieved via AJAX.
When using this method, the server must supply a JSON formatted array named "availableTags" and optionally an additional array named "assignedTags"."
On the clientside you want to load the tag handler like so:
$(document).ready(function()
{
$("#array_tag_handler").tagHandler({
dataType: 'json',
getURL: '/admin/tag/list',
autocomplete: true
});
});
This calls the '/admin/tag/list' route and expects json back.
On the server side you want to retrieve the list of tags and pass them back in json format.
$result = getTags(); // Returns eg array('tag1', 'tag2', 'tag3', etc)
Then build your array with the correct indices according to the Tag Handler documentation:
$data = array('availableTags' => $result);
Note that if you want to preload some tags (eg tag1 and tag2) then just modify the array above so that it looks like this:
$data = array('availableTags' => $result, 'assignedTags' => array('tag1', 'tag2'));
Then you need to json encode this array before returning it to the client:
return json_encode($data);

Categories