javascript: get value inside a nested array - javascript

I finally managed to write a raw INSERT-query with sequelize/Apollo/ExpressJS and it returns a json like
{"data":{"createActie":"[[{\"id\":1598}],1]"}}.
I can get to [[{\"id\":1598}],1] by
await this.$apollo
.mutate({
mutation: CREATE_ACTIE_QUERY,
variables: {
// ...
}
})
.then(response => {
console.log(response.data.createActie);
})
but now i want to extract the id and i struggle to say the least (i am not a trained javascript developer, just trying to learn by reading and experimenting)

the solution was adding json.parse...
JSON.parse(response.data.createActie)[0][0].id

Related

Currently learning svelte and need some assistance

Currently I am trying to create a hacker news clone (not from the example given on website). Currently I made an api call that returns an array but I can't seem to get rid of the square brackets. For reference my code is below
onMount(() => {
fetch('https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty&limitToFirst=10&orderBy="$key"')
.then((res) => {
return res.text();
})
.then((text) => {
items = text.split(",");
setTimeout(3000);
data = items.filter((val) => {
return val.replace(/[\[\]']+/g, "");
});
});
//console.log(data);
//getData(items).then(console.log);
});
Thanks in advance!
The API provides a JSON object, but you read it as text (res.text()). Replace this with res.json() and the result will automatically be parsed to an array of IDs.
There is no need to manipulate JSON in string form, just parse it/let it be parsed.

Delete Firebase Users programmatically with Node.js

I use the Firebase SDK with Node.js and try to delete a bulk of accounts programmatically (identified by their email address).
What does work is to hardcode those accounts in my firebase-delete-users.js file like this:
const uids = [
{email: 'user1#example.com'},
{email: 'user2#example.com'},
];
const markedForDelete = [];
// Retrieve a batch of user accounts.
admin.auth().getUsers(uids)
.then((result) => {
result.users.forEach((user) => {
markedForDelete.push(user.uid);
});
result.notFound.forEach((uid) => {
console.log(`No user found for identifier: ${JSON.stringify(uid)}`)
});
})
.then(() => {
// Delete all marked user accounts in a single API call.
return admin.auth().deleteUsers(markedForDelete);
});
But it does no longer work if I try to get those elements out of a .txt file, where each line is one array-element.
var uids = fs.readFileSync("accounts-to-delete.txt", 'utf8').toString().split("\n");
accounts-to-delete.txt :
{email: 'user1#example.com'}
{email: 'user2#example.com'}
The console log also doesn't look exactly the same if I compare uids and uids2 but I don't understand the reason and how to solve it:
var uids = fs.readFileSync("accounts-to-delete.txt", 'utf8').toString().split("\n");
const uids2 = [
{email: 'user1#example.com'},
{email: 'user2#example.com'},
];
for(i in uids) {
console.log(uids[i]);
}
for(i in uids2) {
console.log(uids2[i]);
}
If it helps to find a solution:
It doesn’t have to be a .txt file if .json or some other filetype fits better for this use case.
Reading text from a file and iterating elements of an array of objects are completely different tasks. They have little on common, other than iteration.
Your bit of code that iterates an array of objects is simply taking advantage of the fact that the data in uids2 is already structured as Javascript arrays and object. It doesn't work the same for reading lines of raw text out of a file.
Your bit of code that reads the file is not able to assume the JSON structure of the data in its raw form. uids is just an array of strings. You will have to parse the JSON and turn each line into actual JavaScript objects using JSON.parse(). Something like this might work:
var uids = fs
.readFileSync("accounts-to-delete.txt", 'utf8')
.toString()
.split("\n")
.map(line => JSON.parse(line));
With this uids not just an array of strings, as it was before. It's now an array of JavaScript objects that are easier to work with.
fs.readFileSync("accounts-to-delete.txt", 'utf8').toString().split("\n"); returns an array of strings instead an array or objectsm which is what you want.
So you can use JSON.parse() to parse each split line.

Retrieve article object including its image using the Shopify JavaScript Buy SDK custom query

I'm using the shopify-buy SDK to try and fetch the articles off of my Shopify store just using JavaScript on the frontend, following the "Expanding the SDK" directions here: https://shopify.github.io/js-buy-sdk/#expanding-the-sdk.
Using the code below, I am able to retrieve my articles and some of the fields that I need.
// Build a custom query using the unoptimized version of the SDK
const articlesQuery = client.graphQLClient.query((root) => {
root.addConnection('articles', {args: {first: 10}}, (article) => {
article.add('title')
article.add('handle')
article.add('url')
article.add('contentHtml')
})
})
// Call the send method with the custom query
client.graphQLClient.send(articlesQuery).then(({model, data}) => {
console.log('articles data')
console.log(data)
})
However, I really need to pull the featured image for each article as well, and unfortunately, when I add the line article.add('image') in my articlesQuery, the resulting articles data logs null. I tried building a custom productsQuery, and that has a similiar problem - I can retrieve some of the product fields, but when I try add the line product.add('images'), I just get null back from the storefront API.
Does anyone have experience building custom/expanded queries and successfully retrieving images?
Try following:
// Fetch all products in your shop
client.graphQLClient.fetchAll().then((acticles) => {
console.log(acticles);
});
And then check in console what sort of available property names your articles have. If SDK allows you get any image data, there should be for sure anything like imageSrc || imageUrl || img......
Thanks to Rebecca Friedman on the js-buy-sdk repo's github issues section for providing this working solution:
const articlesQuery = client.graphQLClient.query((root) => {
root.addConnection('articles', {args: {first: 10}}, (article) => {
article.add('title')
article.add('handle')
article.add('url')
article.add('contentHtml')
article.addField('image', {}, (image) => {
image.add('id')
image.add('originalSrc')
})
})
})
// Call the send method with the custom query
client.graphQLClient.send(articlesQuery).then(({model, data}) => {
console.log('articles data')
console.log(data) // works!
})
Because the image field is its own object, you have to add a callback function to specify the fields you need.

Userless Authentication Foursquare API "Missing access credentials" - 400 error

Bit of a weird one. I'm building a React js app interacting with the Foursquare API, mainly just to learn about React js and APIs.
I'm using Foursquare to get Venue information, that works fine. I also want to use it to get venue photos which is where the fun starts.
The method that processes the original call to venues is as follows. I'm just putting this here for to provide a control as this works fine. It returns the venue information which i process within the app with no problem:
getVenues: (searchTerm) => {
const urlToFetch =
${urlExplore}${searchTerm}&limit=10&client_id=${clientId}&client_secret=${clientSecret}&v=20180602;
return fetch(urlToFetch).then( response => {
return response.json();
}).then( jsonResponse => {
if (jsonResponse.response.groups[0].items) {
return jsonResponse.response.groups[0].items.map(item => (
{
id: item.venue.id,
name: item.venue.name,
// blah
}
));
} else {
return [];
}
})
}
So far, so good, it works fine. However, when I try the same approach accessing the photos endpoint, the method returns a series of objects containing meta which says:
​ code: 400
​​ errorDetail: "Missing access credentials. See
https://developer.foursquare.com/docs/api/configuration/authentication for
details."
​​errorType: "invalid_auth"
Suffice to say the information at the link provided doesn't actually give much help :-(
The method I'm using to get the photo information is:
getVenuePhotos: (venueId) => {
const fetchPhotosURL = `${urlPhotos}${venueId}/photos&limit=10&client_id=${clientId}&client_secret=${clientSecret}&v=20180602`;
return fetch(fetchPhotosURL).then( response => {
return response.json();
}).then( jsonResponse => {
console.log(jsonResponse);
//blah - removed to save space - see method above, it's pretty much the same
})
}
...both are stored in an object in a separate file which the react component imports.
The url vars resolve as follows (asterisks are my addition):
fetchVenuesURL: https://api.foursquare.com/v2/venues/explore?near=london&limit=10&client_id=**** &client_secret=****&v=20180602
fetchPhotosURL: https://api.foursquare.com/v2/venues/4ac518eff964a52064ad20e3/photos&limit=10&client_id=**** &client_secret=****&v=20180602
Does anyone have any idea why this might be happening?
thanks in advance
I think there is a typo in your URL.
Replace
${urlPhotos}${venueId}/photos&limit=10&client...
with
${urlPhotos}${venueId}/photos?limit=10&client...

Array undefined javascript

Hello my problem is that i get undefined , when trying to accsess the array length, but everything works fine when i try to access only the array.
this above do not works ->
console.log(this.ref_number_response[0].info.length);
This works ->
console.log(this.ref_number_response);
and this is the whole
check_ref_number: function () {
this.ref_number_response = [];
axios.get('/is_referenceNumber_free/'+this.ref_number)
.then(response => this.ref_number_response.push({
info: response.data
}));
console.log(this.ref_number_response[0].info.length);
Event.$emit('reference_added', this.ref_number_response);
},
Emit the event after you recieve the data:
check_ref_number: function () {
axios.get('/is_referenceNumber_free/'+this.ref_number)
.then(response => Event.$emit('reference_added',[{info:response.data}]));
}
The problem is that you are getting the data asynchronously, and trying to use the data before it is ready.
You said you are trying to access the the array length, but
this.ref_number_response
is the array, so the only way this console.log(this.ref_number_response[0].info.length); is going to work ( you're trying to get the info property from first element of the array length not the actual array length ) is if info were an array as well. So you'd probably need to do something like:
console.log(this.ref_number_response.length);

Categories

Resources