How to replace a object inside JSON array with a fetch - javascript

I have a JSON that looks like this:
[{
is_email_opt_in: false,
credit_card_type: 'visa',
order_source: 'www',
channel_id: 1,
external_source: '',
products: {
url: 'https://api.bigcommerce.com/stores/XXX/v2/orders/149/products',
resource: '/orders/149/products'
}
}]
I'm trying to replace all "products" fields with the a fetch result that comes from BigCommerce API based on the value of the products.resource key.
This is my current code:
result = await this.instanceV2.get(`/orders`);
if (result)
result.forEach(
async (order) =>
(order.products = await this.instanceV2.get(
order.products.resource
))
);
But it's not working, the field doesn't get replaced.

Related

how to convert an array to a array of objects with additional information in react using map when doing a POST api request

I'm new with react and I'm stuck at a problem, kindly help me.
array looks like this:
surveyors=[jj,kk]
The length of array can be variable i.e.there can be more values.
what i want to send in post api is:
data:[
{
name:"kk",
is_active:True,
company:26
},
{
name: "jj",
is_active:True,
company:26
}
]
I'm using postapi like this:
const postURL = moduleURL("url");
requests({
method: "post",
url: postURL,
data: [
{
name:"kk",
is_active:True,
company:26
},
{
name: "jj",
is_active:True,
company:26
}
],
})
.then((response) => {
console.log(response);
})
.catch((err) => console.log(err));
}
if there was a fixed data i could do it but since the data in array surveyor is variable i cannot fix it.
note- company here is the company id that i have stored in a variable and it will be same for every object in array and is_active will always be true.
var supervisor=["jj","kk"];
var result = supervisor.map(s => {return {name: s, is_active:true, company:26} });
console.log(result)
use map to create a new array of objects with extra attributes;
const supervisors = ["jj", "kk"];
const modifiedSupervisors = supervisors.map(item => ({name: item, is_active:true, company:26}));
now you can use this data in api call data: modifiedSupervisors,

How to get object array generated by axios get

(async() =>{
const axios= require('axios');
const response = await axios("https://graph.facebook.com/v13.0/110524034851999/feed?limit=3&access_token=×××××××");
const data = response.data;
console.log(data);
console.log(data[0]);
})();
Above is the code I am using to get json from Facebook API I am getting an object as below
data: [
{
created_time: '2022-04-14T14:01:45+0000',
message: 'How to make jw',
id: '...'
},
{
created_time: '2022-04-14T14:01:19+0000',
message: 'Testing',
id: '....'
},
{
created_time: '2022-04-14T01:51:41+0000',
message: 'Enriqueta',
id: '.....'
}
],
I am not able to get the data from object using data[0] which should return me first object but it's giving me undefined error how can I get the message which is on first array of data object from the above json?
replace
console.log(data[0]);
with
console.log(data.data[0]);
maybe?

how to iterate over two responses one after another using javascript

I am initialized one variable with two responses from two async calls like this below.
const items = await service.fetchDropdownFieldItems(payload.url);
It is storing the responses one after another and it is working fine. Those responses are like below:
1st response : [{id:1, value:'Shoe'},{id:2,value:'Boutique'},{id:3,value:'Clothing'}]
2nd response: {data:[{country_id:1, country_name:'Australia'},{country_id:2,country_name:'France'},{country_id:3,country_name:'USA'}]}
Now, i want to format 2nd response's data array and replace the 2nd response with my formatted response.
Now, if i check items variable it should contain like this
1st response : [{id:1, value:'Shoe'},{id:2,value:'Boutique'},{id:3,value:'Clothing'}]
2nd response: [{id:1, value:'Australia'},{id:2, value:'France'},{id:3, value:'USA'}]}
Any approach for doing like this. There is no issue on async call or url etc. Only i want to change the response and replace with old one.
const formattedResponse = response.data.map((entry)=>({
id: entry.country_id,
value: entry.country_name
} ) )
you might place this logic somewhere inside service.fetchDropdownFieldItems, so you don't need to manually change your data everytime you fetch the items
Edit
Here is an example of how to use it inside a fetching function. You can change fetch with axios if you prefer
const formatResponse=(data)=>{
return data.map((entry)=>({
id: entry.country_id,
value: entry.country_name
} ) )
}
const fetchDropdownFieldItems =(url, options={})=>{
return fetch(url, options)
.then(res=> res.json())
.then(res=>res.data)
.then(formatResponse) //shorthand for .then(data=> formatResponse(data)
}
Use it as follows:
fetchDropdownFieldItems(...).then(doSomething)
//same as
fetchDropdownFieldItems(...).then(formattedData => doSomething(formattedData))
[].map should do the trick
const res2 = {
data: [{
country_id: 1,
country_name: 'Australia'
}, {
country_id: 2,
country_name: 'France'
}, {
country_id: 3,
country_name: 'USA'
}]
}
const result2 = res2.data.map(v => ({
id: v.country_id,
value: v.country_name
}))
console.log(result2)
const processData = (response) => {
const dataArray = [];
response.data.forEach(({country_id,country_name})=>{
dataArray.push({ id: country_id, value: country_name });
})
return dataArray;
}
This answer is the same as previous one but, takes less time to execute, and a little bit optimized
or also be used as
const processData = (response) => {
return response.data.map(({country_id,country_name})=>({ id: country_id, value: country_name }))
}

res.json() sends data in the form of res.data but accessing _id within it is undefined

I'm having trouble understanding why a res.json call in my app sends data (an order object) but when I try accessing a piece of that data (res.data._id) and storing it into a variable I get it as undefined. I know this piece of data exists since the console.log shows the order object's _id value but console.logging that particular piece returns undefined. What causes this behavior?
Backend logic:
router.post("/new", function(req, res) {
const productInfo = req.body.productInfo;
let order = new Order();
order.product = {
_id: productInfo.id,
name: productInfo.name,
description: productInfo.description,
price: productInfo.price,
quantity: productInfo.quantity
}
order.status = "Created";
order.total = productInfo.price * productInfo.quantity;
order.owner = {
id: req.body.id,
username: req.body.username
}
order.save().then(order => {
res.status(200).json(`Order created successfully! Created order details: ${order}`);
}).catch(err => {
console.log("Order create error: ", err.message);
});
});
Frontend logic:
let orderID = "";
return (
<PayPalButton
createOrder={(data, actions) => {
axios.post("http://localhost:4000/orders/new",
{productInfo, userID, username}
).then((res) => {
if(res.status === 200) {
console.log(res.data);
console.log(res.data._id)
orderID = res.data._id;
}
}).catch((err) => {
console.log(err);
});
return actions.order.create({
purchase_units: [{
amount: {
currency_code: "USD",
value: props.amount
}
}]
})
}}
/>
)
console.log response:
Order created successfully! Created order details: { product:
{ _id: '5e68330c8dcfa56868f1d23a',
name: 'Birdhouse',
description: 'A beautiful birdhouse',
price: 5,
quantity: 2 },
owner: { username: 'tgoandrex' },
createdAt: 2020-04-12T23:04:46.286Z,
_id: 5e93a16eb1cbc837d80167ef,
status: 'Created',
total: 10,
__v: 0 }
undefined
axios is expecting the endpoint to return a JSON object, but you're sending a string to the client:
res.status(200).json(`Order created successfully! Created order details: ${order}`);
Attempting to access res.data on the client will give you the string literal
"Order created successfully! Created order details: [elided]"
But because this is a string, the property _id does not exist on it, and so it will return undefined.
In order for this to work, you need to send just the object, rather than a string:
res.status(200).json(order);
Your /orders/new endpoint doesn't respond with JSON but with a simple string. Express's Response#json method is expecting an object that will be serialized to JSON, not a string.
You should just pass your order as single argument to the json method:
res.status(200).json(order);
otherwise, your React app won't be able to parse the JSON since it isn't a valid JSON format.

Make data in JSON be it's own attribute in Dynamodb?

Whenever I call a post API to my dynamodb, all the data gets store in one "content" attribute. Is there a way to have a separate attribute for each attribute in the JSON structure?
For instance here is where I am calling the API, the JSON structure of data is in the values variable.
export default (async function submitSite(values) {
console.log(values);
createSite(values);
})
function createSite(site) {
return API.post("sites", "/sites", {
body: site
});
}
and here is the code for the API itself:
export async function main(event, context) {
const data = JSON.parse(event.body);
console.log(data);
var site = "IE"+data.siteCounty+data.siteName;
var siteIdStripped = site.replace(/[aeiou]/g, '');
var siteId = siteIdStripped.replace(/ /g,'');
var siteIdFinal = siteId.toUpperCase();
const params = {
TableName: "sites",
Item: {
userId: event.requestContext.identity.cognitoIdentityId,
siteId: siteIdFinal,
content: data,
createdAt: Date.now()
}
};
When I upload it is has the structure siteId, userId, content(with an object of data), created at.
Id like for it to be displayed as siteId, userId, siteName, siteAddress, etc etc the last 2 being one of the indexes in the json
You are explicitly creating the content attribute here: content: data,. You either need to explicitly set each attribute like this:
Item: {
userId: event.requestContext.identity.cognitoIdentityId,
siteId: siteIdFinal,
siteName: data.siteName,
siteAddress: data.siteAddress,
createdAt: Date.now()
}
Or, you could simplify this with the object spread operator like so:
Item: {
...data,
userId: event.requestContext.identity.cognitoIdentityId,
siteId: siteIdFinal,
createdAt: Date.now()
}

Categories

Resources