How to use JSON response as an array in javascript - javascript

Here is my response I get from API request:
[ 'bookShelf3', 'bookShelf4', 'bookShelf5' ]
Here is a part of my code which searches through my mongoDB Databese:
const responseToSearchC = (req, res) => {
console.log(req.body.searchTerm);
db.collection('subtitle')
.find({
series: { $in: ['bookShelf1'] },
$text: { $search: req.body.searchTerm },
})
I just want to make my code dynamic and instead hard coding ['bookShelf1']
set its value by JSON response.
the problem is the response from API is an object (although it is look like an array) and I cannot replace it with my hard codded array ['bookShelf1']
I tried to stringify it but it didn't work cuz its a string again, and not an array like hardcoded one

If the response is really an object like:
{ 0: 'bookShelf3', 1:'bookShelf4', 2: 'bookShelf5'}
you can simply utilize the Object.values() method which returns all of the object's values as an array.
Here's an example:
let ob={ 0: 'bookShelf3', 1:'bookShelf4', 2: 'bookShelf5'};
console.log(Object.values(ob));

Related

Format array for batch api call in Javascript

I have an array with this format:
var customerList = [{'email: ex#mail.com', 'name': 'John'}, {...}, {...}]
However I need to format a batch api call for the following format for each of the objects in the array:
api.post('/:batch_endpoint'), {
0: {url: '/:endpoint', data: {email: customerList[0].email}},
1: {...},
2: {...},
}
So essentially I'm wondering if there's a way to dynamically fill the records for the api call from that array or another list. So far I've tried to use Object.assign() but not sure if this is the right way forward:
var customerObject = Object.assign({}, customerList) outputs:
{
'0': {
email: 'ex#mail.com',
'...',
},
1: {...}
}
Beyond this point I'm not sure how I can format this api call properly.
Assuming that you're asking how to send batch updates as a 1st index-based array (instead of 0th index-based) you have at least a couple of options:
Option 1: Use the reduce method to add one to the key:
customerList.reduce((acc, data, idx) => ({
...acc,
[parseInt(idx) + 1]: {
url: "/:endpoint",
data
}
}), [])
Option 2: Use the unshift method to add a "garbage" value to the 0th index:
// Convert the values in the array into the shape you want to send
customerList.map(data => ({ url: "/:endpoint", data }))
// Insert garbage value at index 0
customerList.unshift(0)
Option 3: Update your API to support 0th indexed-arrays if you plan on sending data frequently. IMO, the above two solutions are a hack and less than ideal. However, this may not be possible in your situation.

Axios turns nested JSON array to empty when posting

I'm trying to post data from Axios to my API but although my json data looks correct when passing to Axios, browser tools tells me that my nested property is empty.
My data contains nested objects and looks like this:
{
'name': 'foo',
'index': 1,
'nested': [
{
'date': '2020-05-10',
'geojson_data': {
'crs': Object,
'name': 'my-name',
'type': 'FeatureCollection',
'features': [{ ... }, { ... }]
}
},
]
}
Edit: geojson_data results from parsing .geojson file, thus, the features array contains ~300 items.
My axios function is defined here:
async post(data) {
console.log(data);
return axios
.post(API_URL + 'endpoint/',
data,
{
headers: authHeader()
})
.then(response => {
return response.data;
})
}
authHeader() is used to provide Bearer token authorization.
I check that data passed to axios is correct (looks like above), but browser tools tell me that data actually sent looks like
{"name":"foo","index":1,"nested":[]}
Why is my array empty ?
Edit: I tried to manually populate a sample nested object and it seems to work. Yet, whenever I use my actual data, it doesn't.
Don't know if it's relevant but in the console, here is the difference I can see between the 2 collapsed objects (actual vs sample):
Sample : Object { name: "foo", index: "1", nested: (1) […] }
Actual : Object { name: "foo", index: "1", nested: [] }
Notice the nested array which looks like it is empty. Yet, if I expand it, they look the same. Any ideas ?
P.S: looks like this SO post from 3 years ago, but without solution

How to get more data with axios?

when I do this:
const uuidapi = await axios.get('https://api.hypixel.net/player?key=mykey&name=' + args[1]);
console.log(uuidapi);
I get this response from Axios:
https://paste.menudocs.org/paste/7vppu
So my question is: How do I get the Data after "socialMedia"? Heres how socialMedia looks like:
"socialMedia": {
"links": {
"YOUTUBE": "https://www.youtube.com/channel/UC1L7H9qQyB2zZgt-1XUv6jA",
"DISCORD": "Altpapier#4847"
}
}
Why does it say socialMedia: [Object], and how do I get more than this?
I can't use const { data } = await axios.get(URL); because I want to get 2 URL responses with the complete data.
I also want to be able to safe for example the DISCORD Name Altpapier#4847 how do I do that?
All the data is already here, it's just the formatting of console.log that's not printing every nested object.
If you replace
console.log(uuidapi);
by
console.log(JSON.stringify(uuidapi));
it will work better
See this question: How can I get the full object in Node.js's console.log(), rather than '[Object]'?
you can use console.dir( yourObject, { depth: null } )

Angular $resource response is not treated as Array

My server is sending a response with Array inside of Array:
[
[{1:1},{1:2}],
[{2:1},{2:2}]
]
I'm not able to execute array functions on the internal array.
I'm able to execute forEach on the outer array, but not on the internal ones.
Here's my service:
return $resource('api/blablabla/:blablaId', {
blablaId: '#_id'
}, {
'query': {method: 'GET', isArray: true}
});
so far I've tried using:
myData=angular.toJson(myData)
and
myData=JSON.parse(angular.toJson(myData))
But it hasn't worked. In fact, they gave the following output:
{"0":{"1":1},"1":{"1":2}}
angular.forEach worked, but I need some other array functions too.
if you are sure that response data will be array of array list, then you can iterate using below code. there is no need to convert it into json.
a.forEach(function(a1){
a1.forEach(function(item) {
for( var key in item ) {
console.log(item[key])
}
})
})

Mongodb: Find ids $in nested array property

I have the following data structure for my users in my mongodb:
{
_id: "someId",
profile: {
username: "oliv",
friendRequests: [
{ fromUserId: "anId", accepted: false, created: "someDate"},
{ fromUserId: "otherId", accepted: true, created: "otherDate"}
]
}
I'd like to retrieve the user objects that are referenced in my logged user's friendsRequested.
So I tried something like this:
Meteor.users.find({_id: {$in: Meteor.user().profile.friendRequests.fromUserId}});
// FYI: Meteor.users is the collection and Meteor.user() retrieves the current user
But it's not working. I'm assuming it's because of the nested array.
Is there any way of telling mongo to iterate through the fromUserId or something?
Thanks
Change your query to:
Meteor.users.find({_id: {$in: _.pluck(Meteor.user().profile.friendRequests, 'fromUserId') }});
Reasoning:
friendRequests is an array of objects, and $in wants an array of strings(the ids), using _.pluck you're able to pass an array of objects, and tell _ to only return the field fromUserId for each object in the array.
Question in comment ("what if I only want to get the ids from friend requests where "accepted" is false?"):
_.pluck(
_.filter(Meteor.user().profile.friendRequests, function (req) {
return !req.accepted;
}),
'fromUserid'
);
Underscore filter docs

Categories

Resources