Parsing an api response - reactjs

I want to parse this api response to get the image url and I find it a little confusing actually because I'm new with apis.
{
"id": "123",
"item": [
{
"picture": {
"type_id": "2",
"url": [
"./img.jpg"
],
"is_in_description": 0,
"gallery": {
"url": "",
"url_id": ""
},
"layout_id": "2",
"variation_name": ""
},
"lister_id": "12345"
}
]
}
Here is my code for fetching the api, can anyone help me with that
fetch(url2,{
method: 'GET'
})
.then((response)=> response.json())
.then((responseJson) => {
const newImg = responseJson.item.map( => {
return{
const img =
};
})
const newState = Object.assign({}, this.state, {
items: newItems
});
console.log(newState);
this.setState(newState);
})
.catch((error) => {
console.log(error)
});

Use the map method for parsing as
var x = {
"id": "123",
"item": [
{
"picture": {
"type_id": "2",
"url": [
"./img.jpg"
],
"is_in_description": 0,
"gallery": {
"url": "",
"url_id": ""
},
"layout_id": "2",
"variation_name": ""
},
"lister_id": "12345"
}
]
}
x.item.map(data=>{console.log(data.picture.url)}) //hope you need the url object

Related

How can I get the totalPrice of product inside a nested document?

How can I get the total price of specific item, I'm trying to multiply the quantity and the price and then POST it, but I'm having a hard time on how can I save the total amount of specific item
OrderSchema.js
const OrderSchema = new mongoose.Schema({
userId: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
products: [
{
productId:{
type: mongoose.Schema.Types.ObjectId, ref: 'Product'
},
quantity: {
type: Number,
default: 1,
},
sellerId: {
type: mongoose.Schema.Types.ObjectId, ref: 'User'
},
totalPrice: {
type: Number,
default: 0,
}
}
],
}, {timestamps: true}
)
export default mongoose.model('Order', OrderSchema)
Order.js
const handleSubmit = async (e) =>{
e.preventDefault()
if(orderSummary?.location === ""){
toast.error("Please input location..")
}else{
try {
await userRequest.post(`/order`,{
userId: currentUser._id,
products: cart.products.map((item) =>({
productId: item._id,
quantity: item.quantity,
sellerId: item.seller_id._id,
totalPrice: Number(item.quantity * item._id.price)
})),
})
} catch (error) {
toast.error("Please put a Location and Time!")
}
}
}
in this image, I want to get the total amount of specific product, so the first product should have a 369.
But when I call my get all orders, this is what I get
{
"_id": "63b1b4de5a95bd4df7f9443b",
"userId": {
"_id": "63b18af8363f51fa50801dd0",
"studentId": "1234567892"
},
"products": [
{
"productId": {
"_id": "63b16fc58fe585c7b81c748d",
"title": "asd",
"price": "123"
},
"quantity": 3,
"sellerId": {
"_id": "63b160689f50f852e056afaf",
"studentId": "1234567890"
},
"_id": "63b1b4de5a95bd4df7f9443c"
},
{
"productId": {
"_id": "63b16ff08fe585c7b81c7496",
"title": "asd21",
"price": "213"
},
"quantity": 3,
"sellerId": {
"_id": "63b160689f50f852e056afaf",
"studentId": "1234567890"
},
"_id": "63b1b4de5a95bd4df7f9443d"
}
],
}
What I'm trying to get here when I call order.js
{
"_id": "63b1b4de5a95bd4df7f9443b",
"userId": {
"_id": "63b18af8363f51fa50801dd0",
"studentId": "1234567892"
},
"products": [
{
"productId": {
"_id": "63b16fc58fe585c7b81c748d",
"title": "asd",
"price": "123"
},
"quantity": 3,
"sellerId": {
"_id": "63b160689f50f852e056afaf",
"studentId": "1234567890"
},
"totalPrice": "369"
},
{
"productId": {
"_id": "63b16ff08fe585c7b81c7496",
"title": "asd21",
"price": "213"
},
"quantity": 3,
"sellerId": {
"_id": "63b160689f50f852e056afaf",
"studentId": "1234567890"
},
"totalPrice": "639"
}
],
}
You can use a virtual field to calculate the totalPrice value:
const OrderSchema = new mongoose.Schema(
{
userId: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
products: [
{
productId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Product",
},
quantity: {
type: Number,
default: 1,
},
sellerId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
// NOTE: Remove this
// totalPrice: {
// type: Number,
// default: 0,
// },
},
],
},
{
timestamps: true,
// NOTE: Add this or it may not work
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
);
OrderSchema.virtual("totalPrice").get(function () {
if (!this.productId) return undefined; // Guard clause in case it is not populated
return this.productId * this.quantity;
});
export default mongoose.model("Order", OrderSchema);
This acts almost exactly like a normal field, however, it is not actually a part of the document. So if you were to query for the least totalPrice, it would act as if the field does not exist.
Pros:
Very performant, since it does not query data
Does not require any complex/hard to read code for such a simple task
Cons:
Requires the productId field to be populated
Cannot be searched in a query
Given that in most cases, you WILL need the productId field populated, this is a better suited solution. Let me know if there are any errors, since I can't really test this without making a whole project.

How to add a quantity in paypal orders in reactjs

I'm trying to add the qty of an order. this is what I have and it wont work :(.
it works without qty but then it defaults to 1. Also how would i add a second product? it will only allow me to have the one
window.paypal.Buttons({
createOrder: (data, actions, err) => {
return actions.order.create({
intent: "CAPTURE",
purchase_units: [
{
description: "cool tablet",
amount: {
currency_code: "CAD",
value: 650.00,
},
quantity: 2,
},
{
description: "ink",
amount: {
currency_code: "CAD",
value: 777.00,
}
}
]
})
},
onApprove: async (data, actions)=>{
const order = await (actions.order.capture());
console.log(order);
},
onError: (err) => {
console.log(err);
}
})
.render(paypal.current)
}, []);
You need a single purchase unit, a single amount with the required breakdown object, and an items array with line item detail. See the API reference at https://developer.paypal.com/docs/api/orders/v2/#orders_create
Here is an example:
"purchase_units": [{
"description": "DESCRIPTION GOES HERE",
"amount": {
"value": "3.00",
"currency_code": "CAD",
"breakdown": {
"item_total": {
"currency_code": "CAD",
"value": "3.00"
}
}
},
"items": [
{
"name": "item one",
"quantity": "1",
"unit_amount": {
"currency_code": "CAD",
"value": "1.00"
}
},
{
"name": "item two",
"quantity": "1",
"unit_amount": {
"currency_code": "CAD",
"value": "2.00"
}
}
]
}
]

Filter data of an array in setState in reactjs

In the code below, I am trying to make an array and remove duplicates from array with reactjs:
The array called names is set in state:
this.state = {
names = []
}
How can I remove the duplicated names and place them into the array
const data = [
{
"obj": {
"no": "1",
"info": [
{
"name": "maya"
},
{
"name": "mina"
}
]
}
},
{
"obj": {
"no": "2",
"info": [
{
"name": "maya"
}
]
}
},
{
"obj": {
"no": "3",
"info": [
{
"name": "mina"
},
{
"name": "Mike"
}
]
}
}
]
data.map((elem) => {
for(let i = 0 ; i < elem.info.length;i++){
let name_info = elem.info[i].name
this.setState({
names: [...this.state.names, name_info]
})
}
})
expected output :["maya","mina",Mike]
If you're fan of one line
[...(new Set(data.map(d => d['obj']['info']).flat().map(info => info['name'])))]
Step by step explanation:
First map takes the input returns only info part of each entry:
data.map(d => d['obj']['info']) yields array of array containing info.
[[{ name: "maya" }, { name: "mina" }], [{ name: "maya" }], [{ name: "mina" }, { name: "Mike" }]]
flat() takes the input from previous map which is the array of array and yields array of elements, so it becomes
[{ name: "maya" }, { name: "mina" }, { name: "maya" }, { name: "mina" }, { name: "Mike" }]
map() takes the input from previous flat which is array of object (which contains name) and returns array of name value.
So you got [ "maya", "mina", "maya", "mina", "Mike" ]
The final array is given to Set, by definition set cannot contain same element more than one. Set of previous array is [ "maya", "mina", "Mike" ].
As final step, set is converted to the array by using spread operator.
const data = [
{
"obj": {
"no": "1",
"info": [
{
"name": "maya"
},
{
"name": "mina"
}
]
}
},
{
"obj": {
"no": "2",
"info": [
{
"name": "maya"
}
]
}
},
{
"obj": {
"no": "3",
"info": [
{
"name": "mina"
},
{
"name": "Mike"
}
]
}
}
];
let names = [];
data.forEach(item => {
Object.values(item)[0].info.forEach(person => {
if(names.indexOf(person.name) === -1)
{
names.push(person.name)
}
})
})
console.log(names);
I think this can help you
First, this is a helper function to get just the unique value of an array
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
}
And, this is how can get the result you want
const newNames = data.map((elem) => elem.obj.info.map(info => info.name)).flat().filter(onlyUnique)
You can then use it like this
this.setState({
names: [...this.state.names, ...newNames]
})
const data = [{
"obj": {
"no": "1",
"info": [{
"name": "maya"
}, {
"name": "mina"
}]
}
}, {
"obj": {
"no": "2",
"info": [{
"name": "maya"
}]
}
}, {
"obj": {
"no": "3",
"info": [{
"name": "mina"
}, {
"name": "Mike"
}]
}
}]
const names = data.flatMap(obj => obj.obj.info.map(info => info.name));
const unique = names.filter((name, i) => names.indexOf(name) === i);
console.log(unique);

Unable to loop through my postman response

I have this json respone from postman
I want to write a test to return failure if key "value" in the array is < 50.
It would loop through the array once the condition is not met it fails
I have tried this
pm.test('Matches value', () => {
_.each(pm.response.json(), (arrItem) => {
if (arrItem.persID === 'personID_2') {
throw new Error(`Array contains ${arrItem.persID}`)
}
})
});
My response
{
"groups": [
{
"title": "Maids",
"subTitle": null,
"description": null,
"featured": false,
"items": [
{
"id": "1",
"title": "AA",
"subTitle": "AA",
"thumbnail": "AA",
"priceStartingAt": {
"value": 50,
"baseCurrency": "USD",
"exchangeEnabled": true,
"exchangeRates": {
"aed": 3.672973
}
},
"categories": [
"Activity"
]
},
{
"id": "2",
"title": "BB",
"subTitle": "BB",
"thumbnail": "BB",
"priceStartingAt": {
"value": 20.01,
"baseCurrency": "USD",
"exchangeEnabled": true,
"exchangeRates": {
"aed": 3.672973
}
},
"categories": [
"Activity"
]
}
]
}
]
In this case the test should fail because the value in the second array is 20.01
I'm not sure where you copied that code from but it was never going to work as all the references relate to a different response body.
To keep the same convention and have the throw new Error in there you could do this:
pm.test('Value is not below 50', () => {
_.each(pm.response.json().groups[0].items, (arrItem) => {
if (arrItem.priceStartingAt.value < 50) {
throw new Error(`Array contains ${arrItem.priceStartingAt.value}`)
}
})
});
Or you could just check if the items are not below 50 like this.
pm.test('Value is not below 50', () => {
_.each(pm.response.json().groups[0].items, (arrItem) => {
pm.expect(arrItem.priceStartingAt.value).to.not.be.below(50)
})
});

How to filter JSON object array across nested array with in it

I have an object array and i am filtering it against property name "username" like this.
array = [{
"id": 1,
"username": "admin",
"roles": [{
"name": "Administrator"
},
{
"name": "agent"
}
]
},
{
"id": 2,
"username": "admin2",
"roles": [{
"name": "Administrator2"
},
{
"name": "agent2"
}
]
},
{
"id": 3,
"username": "admin3",
"roles": [{
"name": "Administrator3"
},
{
"name": "agent3"
}
]
}
]
and the filter function is like this
transform(array: any, valueToSearch: string): any[] {
return array.filter(e =>
e.username.toLowerCase().indexOf(valueToSearch.toLowerCase())
!== -1);
}
everything works fine, but now i want to filter against the property name "name" in "roles" array in the object. for example i would like to return an object whose "roles" array contains "name" = agent3 , so it should return the whole object which is located at the last in my example. i tried like
return agents.filter(e => e.roles.filter(ee =>
ee.valueToSearch.toLowerCase()) !== -1));
but it didn't work.
this is dmeo
https://stackblitz.com/edit/angular-txchxs?embed=1&file=src/app/agentFilter.pipe.ts
As per the example given by you in the question, i was able to change your existing function like this and i hope this is your requirement..
ngOnInit() {
this.transform(this.array,'agent3');
}
transform(array: any, valueToSearch: string): any[] {
return this.array.filter(e => {
e.roles.filter(ee => {
if(ee.name.toLowerCase() === valueToSearch.toLowerCase() ) {
console.log(e);
this.finalResult = e;
}
})
})
}
Working Stackblitz: https://stackblitz.com/edit/angular-uzgni7
myarray = [{
"id": 1,
"username": "admin",
"roles": [{
"name": "Administrator"
},
{
"name": "agent"
}
]
},
{
"id": 2,
"username": "admin2",
"roles": [{
"name": "Administrator2"
},
{
"name": "agent2"
}
]
},
{
"id": 3,
"username": "admin3",
"roles": [{
"name": "Administrator3"
},
{
"name": "agent3"
}
]
}
];
function myFunction(){
var filtered= myarray.filter((obj)=>{
return obj.username.match(new RegExp(document.getElementById('search').value,'ig'));
});
console.log(filtered);
};
<input type="text" id="search" onkeyup="myFunction()"/>

Resources