My endpoint only accept only 1 object
Axios.post('www.url.com', {
giftAGift: false,
productId: "1030567",
quantity: 1,
storeId: 0,
variantId: ""
})
What I have is an array of object
let object = [{"giftAGift": false, "productId": "1234", "quantity": 1, "storeId": 0, "variantId": ""}
{"giftAGift": false, "productId": "12345", "quantity": 1, "storeId": 0, "variantId": ""}
{"giftAGift": false, "productId": "123456", "quantity": 1, "storeId": 0, "variantId": ""}
{"giftAGift": false, "productId": "`123456", "quantity": 1, "storeId": 0, "variantId": ""}]
What is the best way to make a post request when I want to send all data when I press only 1 time.
Then you must loop through the array and make an API call for each.
let array = [{"giftAGift": false, "productId": "1234", "quantity": 1, "storeId": 0, "variantId": ""}
{"giftAGift": false, "productId": "12345", "quantity": 1, "storeId": 0, "variantId": ""}
{"giftAGift": false, "productId": "123456", "quantity": 1, "storeId": 0, "variantId": ""}
{"giftAGift": false, "productId": "`123456", "quantity": 1, "storeId": 0, "variantId": ""}]
array.forEach((obj) => {
Axios.post('www.url.com', obj);
})
Edit. Using Promise.allSettled
const promises = array.map((obj) => {
return Axios.post('www.url.com', obj).then((response) => response.data);
});
Promise.allSettled(promises)
.then(() => ...)
.catch(() => ...)
.finally(() => ...)
Well its not good practice because you are inserting multiple records at a time. You should make multiple insert backend route for handling this.
So after this in one API call you can insert e.g., 30 records instead of 30 multiple requests.
But if you still want to make multiple requests then you can done job using following code:
let array = [{"giftAGift": false, "productId": "1234", "quantity": 1, "storeId": 0, "variantId": ""},
{"giftAGift": false, "productId": "12345", "quantity": 1, "storeId": 0, "variantId": ""},
{"giftAGift": false, "productId": "123456", "quantity": 1, "storeId": 0, "variantId": ""},
{"giftAGift": false, "productId": "`123456", "quantity": 1, "storeId": 0, "variantId": ""}]
let arr=arr2.map((obj)=>Axios.post('url.com', obj));
let promise=Promise.allSettled(arr).then((data)=>{
console.log(data);
})
Related
I'm trying to create a replies array that has nested child replies.
Ex:
const [replies, setReplies] = useState([
{
id: 1,
user: "user1",
comment: "test"
replies: [] //In here should be another array that contains other reply objects
},
{
id: 2,
user: "user2",
comment: "test2"
replies: [{
id: 1,
parent_id: 1,
user: "user2",
comment: "test2"
replies: []
}]
}
])
Data is requested through axios from a MySQL database and I have two separate tables for a parent reply and a child reply. The child replies must be included inside replies object - inside the parent reply array like above.
How can I achieve this? (React v17.0.2)
--- updated
Here's what the actual JSON response looks like;
{
"replies": [
{
"id": 1,
"user_id": 31,
"user_name": "admin",
"replied_to": null,
"post_id": 1,
"replied_time": "2021-12-28 19:00:01",
"description": "test",
"likes": 0,
"dislikes": 0,
"replies": null
},
{
"id": 2,
"user_id": 53,
"user_name": "godfrey",
"replied_to": null,
"post_id": 1,
"replied_time": "2021-12-28 19:20:35",
"description": "test2",
"likes": 0,
"dislikes": 0,
"replies": null
}
],
"child_replies": [
{
"id": 1,
"parent_id": 1,
"user_id": 57,
"post_id": 1,
"replied_time": "2021-12-28 19:30:02",
"description": "test3",
"likes": 0,
"dislikes": 0
},
{
"id": 2,
"parent_id": 1,
"user_id": 59,
"post_id": 1,
"replied_time": "2021-12-28 19:42:02",
"description": "test4",
"likes": 0,
"dislikes": 0
}
]
}
I need the objects inside child_replies to be inserted into replies object inside the parent replies array
import { useEffect, useState } from "react";
export default function App() {
const [replies, setReplies] = useState({
replies: [
{
id: 1,
user_id: 31,
user_name: "admin",
replied_to: null,
post_id: 1,
replied_time: "2021-12-28 19:00:01",
description: "test",
likes: 0,
dislikes: 0,
replies: null
},
{
id: 2,
user_id: 53,
user_name: "godfrey",
replied_to: null,
post_id: 1,
replied_time: "2021-12-28 19:20:35",
description: "test2",
likes: 0,
dislikes: 0,
replies: null
}
],
child_replies: [
{
id: 1,
parent_id: 1,
user_id: 57,
post_id: 1,
replied_time: "2021-12-28 19:30:02",
description: "test3",
likes: 0,
dislikes: 0
},
{
id: 2,
parent_id: 1,
user_id: 59,
post_id: 1,
replied_time: "2021-12-28 19:42:02",
description: "test4",
likes: 0,
dislikes: 0
}
]
});
useEffect(() => {
let parent = replies["replies"];
let childReplies = replies["child_replies"];
function callback(obj) {
const childs = childReplies.filter(
(childObj) => childObj["parent_id"] === obj["id"]
);
let childArray = obj.replies === null ? [] : obj.replies;
childArray = [...childArray, ...childs];
return { ...obj, replies: childArray };
}
const result = parent.map(callback);
setReplies(result);
}, []);
console.log(replies);
return (
<div className="App">
</div>
);
}
I have this response coming from an API ...
{
"current_page": 1,
"data": [
{
"id": 1,
"category_id": 1,
"creator_id": 1,
"instructor_id": 1,
"difficulty_id": 1,
"status_id": 1,
"title": "hebae",
"overview": "Course Overview",
"deleted_at": null,
"created_at": "2020-01-02 15:16:08",
"updated_at": "2020-01-02 15:16:08"
},
{
"id": 2,
"category_id": 1,
"creator_id": 1,
"instructor_id": 2,
"difficulty_id": 1,
"status_id": 1,
"title": "update course 1",
"overview": "Course Overview",
"deleted_at": null,
"created_at": "2020-01-02 15:18:40",
"updated_at": "2020-01-02 15:19:06"
},
{
"id": 3,
"category_id": 1,
"creator_id": 1,
"instructor_id": 1,
"difficulty_id": 1,
"status_id": 1,
"title": "hebaTest",
"overview": "Course Overview",
"deleted_at": null,
"created_at": "2020-01-02 15:24:09",
"updated_at": "2020-01-02 15:24:09"
},
{
"id": 4,
"category_id": 2,
"creator_id": 1,
"instructor_id": 1,
"difficulty_id": 1,
"status_id": 1,
"title": "hebaTest",
"overview": "Adile",
"deleted_at": null,
"created_at": "2020-01-02 15:25:03",
"updated_at": "2020-01-02 15:25:03"
},
{
"id": 5,
"category_id": 2,
"creator_id": 1,
"instructor_id": 1,
"difficulty_id": 1,
"status_id": 1,
"title": "hebaTest",
"overview": "Adile",
"deleted_at": null,
"created_at": "2020-01-02 15:33:06",
"updated_at": "2020-01-02 15:33:06"
},
{
"id": 6,
"category_id": 1,
"creator_id": 1,
"instructor_id": 1,
"difficulty_id": 1,
"status_id": 1,
"title": "Course Title",
"overview": "Course Overview",
"deleted_at": null,
"created_at": "2020-01-05 08:24:56",
"updated_at": "2020-01-05 08:24:56"
},
],
"first_page_url": "http://skillboardbackend-staging.zph2jwe3pc.eu-west-1.elasticbeanstalk.com/api/course?page=1",
"from": 1,
"last_page": 2,
"last_page_url": "http://skillboardbackend-staging.zph2jwe3pc.eu-west-1.elasticbeanstalk.com/api/course?page=2",
"next_page_url": "http://skillboardbackend-staging.zph2jwe3pc.eu-west-1.elasticbeanstalk.com/api/course?page=2",
"path": "http://skillboardbackend-staging.zph2jwe3pc.eu-west-1.elasticbeanstalk.com/api/course",
"per_page": 15,
"prev_page_url": null,
"to": 15,
"total": 29
}
I'm trying to get the "data" array to be defined as "categories" object, and the rest data can stay the same, how to do that with normalizr?
I tried this ...
const { data } = await apiGetAllCategories();
const dataSchema = new schema.Entity("categories");
const coursesSchema = new schema.Entity("info", {
data: [dataSchema]
});
const normalizedData = normalize(data, coursesSchema);
console.log(normalizedData);
But it always gives me the "info" as undefined, and the "result" as undefined ...
What am I doing wrong here?
Your data appears to already be in some reduced/normalized form as I don't see any nested, or repeated data structures. I think a simple array::reduce on your data is sufficient for your needs.
// Reduce data array to map [element.id => element]
const dataObject = data.reduce((dataObject, item) => {
dataObject[item.id] = item;
return dataObject;
}, {});
const data = [
{
id: 1,
category_id: 1,
creator_id: 1,
instructor_id: 1,
difficulty_id: 1,
status_id: 1,
title: "hebae",
overview: "Course Overview",
deleted_at: null,
created_at: "2020-01-02 15:16:08",
updated_at: "2020-01-02 15:16:08"
},
{
id: 2,
category_id: 1,
creator_id: 1,
instructor_id: 2,
difficulty_id: 1,
status_id: 1,
title: "update course 1",
overview: "Course Overview",
deleted_at: null,
created_at: "2020-01-02 15:18:40",
updated_at: "2020-01-02 15:19:06"
},
{
id: 3,
category_id: 1,
creator_id: 1,
instructor_id: 1,
difficulty_id: 1,
status_id: 1,
title: "hebaTest",
overview: "Course Overview",
deleted_at: null,
created_at: "2020-01-02 15:24:09",
updated_at: "2020-01-02 15:24:09"
},
{
id: 4,
category_id: 2,
creator_id: 1,
instructor_id: 1,
difficulty_id: 1,
status_id: 1,
title: "hebaTest",
overview: "Adile",
deleted_at: null,
created_at: "2020-01-02 15:25:03",
updated_at: "2020-01-02 15:25:03"
},
{
id: 5,
category_id: 2,
creator_id: 1,
instructor_id: 1,
difficulty_id: 1,
status_id: 1,
title: "hebaTest",
overview: "Adile",
deleted_at: null,
created_at: "2020-01-02 15:33:06",
updated_at: "2020-01-02 15:33:06"
},
{
id: 6,
category_id: 1,
creator_id: 1,
instructor_id: 1,
difficulty_id: 1,
status_id: 1,
title: "Course Title",
overview: "Course Overview",
deleted_at: null,
created_at: "2020-01-05 08:24:56",
updated_at: "2020-01-05 08:24:56"
}
];
// Reduce data array to map [element.id => element]
const dataObject = data.reduce((dataObject, item) => {
dataObject[item.id] = item;
return dataObject;
}, {});
console.log(dataObject);
For anyone interested in how to normalize this response with "normalizr", I figured out where I went wrong, and that normalizr usually looks for and an "id" key at the top level, and if it can't find that you gonna have to provide it, in my case there was no "id" on the top-level object, so I gave it the "per_page" as an id to make it work ...
const dataSchema = new schema.Entity("data");
const coursesSchema = new schema.Entity( "info",
{
data: [dataSchema]
}, { idAttribute: "per_page" } );
const normalizedData = normalize(data, coursesSchema);
By the way the "answer" provided by #Drew Reese is way simpler and cleaner in this kind of flat object response that I got.
Cheers :)
In current data "children" key will be fix. If there is any child data available then there then it must in list of dictionary format.
If there is no any children available then it no "children" key is available in dictionary.
I don't want to use the loop to bifurcate this data.
I want the same consistent sequence data. Please note there will any number of hierarchy available.
I want all this data in list of dictionary format like given requirement data example.
Current data.
{
"id": 2,
"parent_id": 1,
"name": "0",
"is_active": true,
"position": 1,
"level": 1,
"children": [
{
"id": 8,
"parent_id": 1,
"name": "01",
"is_active": false,
"position": 1,
"level": 2,
"children": [
"id": 9,
"parent_id": 1,
"name": "010",
"is_active": false,
"position": 1,
"level": 2,
"children": [
<'Here N number of hirerchy availabe'>
]
]
},
],
"id": 3,
"parent_id": 1,
"name": "1",
"is_active": true,
"position": 1,
"level": 1,
"children": [
{
"id": 5,
"parent_id": 1,
"name": "03",
"is_active": false,
"position": 1,
"level": 2,
"children": [
"id": 6,
"parent_id": 1,
"name": "030",
"is_active": false,
"position": 1,
"level": 2,
"children": [
<'Here N number of hirerchy availabe'>
]
]
},
]
}
Requirement.
[{
"id": 2,
"parent_id": 1,
"name": "0",
"is_active": true,
"position": 1,
"level": 1,
},
{
"id": 3,
"parent_id": 1,
"name": "01",
"is_active": false,
"position": 1,
"level": 2,
},
{
"id": 3,
"parent_id": 1,
"name": "01",
"is_active": false,
"position": 1,
"level": 2,
},{
<N Number of dictionary data with consistant sequence>
}]
The suitable answer will definitely acceptable.
You can flatten the given nested data structure with a recursive function like this:
def flatten(data):
if isinstance(data, dict):
return [data, *flatten(data.pop('children', ()))]
return [subrecord for record in data for subrecord in flatten(record)]
Demo: https://repl.it/#blhsing/BlankHatefulResources
I have found the solution to my question. Below code is working for me.
if isinstance(categories, dict):
values = {
'name': categories.get('name'),
'parent_id': categories.get('parent_id'),
'magento_id': categories.get('id'),
'instance_id': instance.id
}
self.category_list.append(values)
self._analyse_response_data(categories.get('children_data'), instance)
if isinstance(categories, list):
for category in categories:
values = {
'name': category.get('name'),
'parent_id': category.get('parent_id'),
'magento_id': category.get('id'),
'instance_id': instance.id
}
self.category_list.append(values)
self._analyse_response_data(category.get('children_data'), instance)
return self.category_list
I have used recursion to fulfil my requirement.
{
"userid": 1,
"following": [2, 3],
"salary": 1000,
"age": 19
},
{
"userid": 2,
"following": [],
"salary": 2000,
"age": 25
},
{
"userid": 3,
"following": [2],
"salary": 1500,
"age": 20
},
"following" shows the userid of the people the user follows.
I would like to have an output query showing the userid and the salary of those that he follows only (no need age and the user's salary). I saw that $lookup() could be used but I am unsure of using it.
My desired output is shown below, may I know if it is possible? I am also open to any other outputs. Thank you in advance!
{
"userid": 1,
"following": [{2, 2000}, {3, 1500}]
},
{
"userid": 2,
"following": []
},
{
"userid": 3,
"following": [{2, 2000}]
}
You can use graphLookup to join the collection to itself, then use project stage to exclude unwanted fields like this:
db.collection.aggregate([
{
$graphLookup: {
from: "collection",
startWith: "$following",
connectFromField: "following",
connectToField: "userid",
as: "following",
maxDepth: 0
}
},
{
$project: {
"_id": 0,
"userid": 1,
"following.salary": 1,
"following.userid": 1
}
}
])
The output is not the same as you wanted, but as you said you are open to all suggestions I posted:
[
{
"following": [
{
"salary": 2000,
"userid": 2
},
{
"salary": 1500,
"userid": 3
}
],
"userid": 1
},
{
"following": [],
"userid": 2
},
{
"following": [
{
"salary": 2000,
"userid": 2
}
],
"userid": 3
}
]
Playground:
https://mongoplayground.net/p/WnF1vRY5Avr
I have a JSON result set which is like this
"Default": [
{
"PortalId": 0,
"Price": 990000,
"Featured": false,
"Type": 1,
"Bathrooms": 6,
"Rooms": 5,
"Volume": 0,
"Area": 430,
"CreatedDate": "2017-03-13T18:16:08.38Z",
"ShowFrom": "2017-03-13T18:16:08.38Z",
"ShowTill": "9999-12-31T23:59:59.997Z",
"UserId": 2,
"Kitchen": 1,
"CityId": 46,
"Code": "CA-799",
"Verified": false,
"Plot": 1234,
"CityName": "Capdepera",
"ImageName": "RV5",
"ImagePath": "/Portals/0/RealEstateThumbs/20/RV5.jpg",
"Id": 20,
"Guid": "00000000-0000-0000-0000-000000000000",
"Title": null,
"Modified": "0001-01-01T00:00:00Z",
"_2sxcEditInformation": {
"entityId": 20,
"title": "(no title)",
"isPublished": true
}
},
{
"PortalId": 0,
"Price": 1750000,
"Featured": false,
"Type": 1,
"Bathrooms": 6,
"Rooms": 5,
"Volume": 0,
"Area": 360,
"CreatedDate": "2017-03-10T10:25:42.647Z",
"ShowFrom": "2017-03-10T10:25:42.647Z",
"ShowTill": "9999-12-31T23:59:59.997Z",
"UserId": 2,
"Kitchen": 1,
"CityId": 61,
"Code": "ES-9337",
"Verified": false,
"Plot": 1234,
"CityName": "Esporles",
"ImageName": "RV6",
"ImagePath": "/Portals/0/RealEstateThumbs/21/RV6.JPG",
"Id": 21,
"Guid": "00000000-0000-0000-0000-000000000000",
"Title": null,
"Modified": "0001-01-01T00:00:00Z",
"_2sxcEditInformation": {
"entityId": 21,
"title": "(no title)",
"isPublished": true
}
}
When I add a ValueFilter to the Visual Query with a test parameter: [QueryString: Code]=SP
It does not filter on this Code value (in above example, those two results should not be returned).
What am I doing wrong?
The ValueFilter itself is defined as:
Attribute = Code
Value = [QueryString: Value]
Operator: begins
Take: all
It is the key to my solution.
I believe the space in the token [QueryString: Code] is your problem - don't use spaces in tokens.