Mapping data from Object of Objects in React - javascript

I am fetching some data from an api and I want to map through it inorder to get all the values inside . But I am unable to do so . Need some help.
Here's the data :
{
'id:5': {
1: {
coinid: 5,
coinname: 'Chainlink',
publishedAt: '2021-06-24T11:10:54Z',
source: 'Cointelegraph',
title:
'asset manager qr launches bitcoin etf on brazilian stock exchange',
description:
'in contrast to hashdexs crypto etf product qr asset managements product provides exposure to bitcoin exclusively',
url: 'https://cointelegraph.com/news/asset-manager-qr-launches-bitcoin-etf-on-brazilian-stock-exchange',
},
2: {
coinid: 5,
coinname: 'Chainlink',
publishedAt: '2021-06-24T13:39:56Z',
source: 'Business Wire',
title:
'truefi announces new integrations with binance chainlink and sushiswap further embedding into the defi ecosystem',
description:
'san franciscobusiness wire binancetrusttoken announces a suite of deep defi integrations designed to make the truefi platform safer more robust and more lucrative for its users',
url: 'https://www.businesswire.com/news/home/20210624005642/en/TrueFi-Announces-New-Integrations-With-Bina',
},
}
and here is my code for fetching api ( I have to unescape the api data coz it was in escaped form) :
const fetchNews = async () => {
try {
const { data } = await axios.get(
'https://h3iiccq04i.execute-api.ap-south-1.amazonaws.com/dev',
);
console.log(JSON.parse(data));
// setNewsData(JSON.parse(data));
setLoading(false);
} catch (err) {
console.log(err.message);
}
};
here the newsData is an object which I have to map and get all the values such as coinname ,url ,etc . Any help would be really appreciated .

We could use Object.values() to get in an array with all the object values and then iterate over it with a map.
const dataArray = Object.values(data['id:5'])
dataArray.map(...)

Related

Filters in Power BI embed report

I developed a few months ago a NodeJS API to get embed reports from Power BI (using a tenant). I consume this API from an Angular app. Now I want to get the report filtered, and I don't know if this is possible with my actual code.
I used the PowerBI rest API to get the embed report. Reading the docs of microsoft, I see lots of docs like this one, where says that I should create an object with the filters that I want. This is not a problem, but I don't know if this is compatible with mi actual Node API or I should develop a new solution.
My API follows the sample provided by Microsoft, and the code is:
async function getEmbedParamsForSingleReport(
workspaceId,
reportId,
additionalDatasetId
) {
const reportInGroupApi = `https://api.powerbi.com/v1.0/myorg/groups/${workspaceId}/reports/${reportId}`;
const headers = await getRequestHeader();
// Get report info by calling the PowerBI REST API
const result = await axios.get(reportInGroupApi, { headers });
if (result.status !== 200) {
throw result;
}
// Convert result in json to retrieve values
const resultJson = result.data;
// Add report data for embedding
const reportDetails = new PowerBiReportDetails(
resultJson.id,
resultJson.name,
resultJson.embedUrl
);
const reportEmbedConfig = new EmbedConfig();
// Create mapping for report and Embed URL
reportEmbedConfig.reportsDetail = [reportDetails];
// Create list of datasets
let datasetIds = [resultJson.datasetId];
// Append additional dataset to the list to achieve dynamic binding later
if (additionalDatasetId) {
datasetIds.push(additionalDatasetId);
}
// Get Embed token multiple resources
reportEmbedConfig.embedToken =
await getEmbedTokenForSingleReportSingleWorkspace(
reportId,
datasetIds,
workspaceId
);
return reportEmbedConfig;
}
With this I obtain the embed report and send back to my app. Is this solution compatible with filters?
Thanks in advance!
Finally, I came out with a solution. In mi Angular app, I use the library powerbi-client-angular. That allows me to define some configuration in the embed report:
basicFilter: models.IBasicFilter = {
$schema: 'http://powerbi.com/product/schema#basic',
target: {
table: 'items',
column: 'id',
},
operator: 'In',
values: [1,2,3],
filterType: models.FilterType.Basic,
requireSingleSelection: true,
displaySettings: {
/** Hiding filter pane */
isLockedInViewMode: true,
isHiddenInViewMode: true,
},
};
reportConfig: IReportEmbedConfiguration = {
type: 'report',
id: cuantitativeReportID,
embedUrl: undefined,
tokenType: models.TokenType.Embed,
filters: [this.basicFilter],
accessToken: undefined,
settings: undefined,
};
With this, I can avoid passing information to the NodeJS API
Yes, It will work fine with this solution. Please find the relevant code below:
Create a filter object:
const filter = {
$schema: "http://powerbi.com/product/schema#basic",
target: {
table: "Geo",
column: "Region"
},
operator: "In",
values: ["West", "Central"]
};
Add the filter to the report's filters:
await report.updateFilters(models.FiltersOperations.Add, [filter]);
You can refer sample NodeJS application to get embed reports from Power BI.
Please find the the reference here:
https://github.com/microsoft/PowerBI-Developer-Samples/tree/master/NodeJS

Discord.js converting Javascript with console into embeds for discord

So I'm working on a bot right now and when looking at the api I get this as the example of how it'll work.
(async () => {
console.log(await bookwebsite.getHomepage(1))
})()
{
results: [ { bookId: 'web id',
thumbnail: 'thumbnail link',
title: 'book title' },
{ bookId: 'web id',
thumbnail: 'thumbnail link',
title: 'book title' },
{ bookId: 'web id',
thumbnail: 'thumbnail link',
title: 'book title' },
...
],
}
Can anyone lead me in the right direction on how to translate this from a console log script to running it within discord embeds? API WARNING NSFW
I'm not extremely sure what you're meaning as of translating console into embeds but I'm guessing you're trying to format the data returned in the api in to a embed in Discord.
const bookwebsite = require('nhentai-js');
(async () => {
var data = await bookwebsite.getHomepage(1);
data = data.results.slice(0, 25);
if(!data) return message.channel.send('Failed to retrieve data from api. ')
// slices to avoid discord embeds going beyond 25 fields
var embed = new Discord.MessageEmbed()
.setTitle('Results found');
// For each the data that's received(after its trimmed)
data.forEach(d=>{
// For every object inside of data, it takes the name and sets it as a field title and sets the description of the field as the id and thumbnail link.
embed.addField(`Name: ${d.title}`, `ID: ${d.bookId}\nThumbnail: ${d.thumbnail}`)
})
// Embeds done, now need to send into the channel
message.channel.send(embed)
})()
If you need any help further on, please comment below.

AMAZON SNS Push notification payload to android mobile using Node js

Implementation of Amazon SNS push notification to android device using aws-sdk package in NodeJS. I have few implementations mentioned below. Mobile device is displaying push notifications. I want to send data and notification object in payload.
let payload2 = JSON.stringify({
default: 'Naresh',
GCM: JSON.stringify({
notification : {
body : 'great match!',
title : 'Portugal vs. Denmark'
},
data:{
testdata: 'Check out these awesome deals!',
url: 'www.amazon.com'
}
})
});
It's not sending push notifications.
let payload1 = {
"GCM": "{
\"notification\": {
\"title\": \"this one last test in app\",
\"body\": \"mm hello tests\"
},
\"data\": {
\"turnclass\": \"efwfwe\",
\"flight\": \"truejet\"}
}"
};
It's sending push notifications.
sns.publish({ TargetArn: targetArn,
Message: payload1,
MessageStructure: 'json'
}, (error, data) => (error) ? reject(error) : resolve(data));
What is right format to send push notifications?
According to documentation:
When sending platform-specific payloads in messages using the Amazon
SNS console, the data must be key-value pair strings and formatted as
JSON with quotation marks escaped.
Example:
{
"GCM":"{
"data":{
"message":"Check out these awesome deals!",
"url":"www.amazon.com"
}
}"
}
What you are doing in the first payload produces the following output:
{"default":"Naresh","GCM":"{\"notification\":{\"body\":\"great match!\",\"title\":\"Portugal vs. Denmark\"},\"data\":{\"testdata\":\"Check out these awesome deals!\",\"url\":\"www.amazon.com\"}}"}
And that is not a valid format. That happens because you're double JSON.stringify a part of your object. So if you do:
let payload2 = JSON.stringify({
default: 'Naresh',
GCM: {
notification: {
body: 'great match!',
title: 'Portugal vs. Denmark'
},
data: {
testdata: 'Check out these awesome deals!',
url: 'www.amazon.com'
}
}
});
It will produce:
{"default":"Naresh","GCM":{"notification":{"body":"great match!","title":"Portugal vs. Denmark"},"data":{"testdata":"Check out these awesome deals!","url":"www.amazon.com"}}}
Which should work as expected.

Using html-pdf with dynamic data

Currently I am testing html-pdf module to generate pdfs from html. And I have successfully generated one. But the issue is that the text/data in the html is fixed at the moment.
What I am trying to do is have an html form on the front-end which the user fills and then generate a pdf which includes the content the user typed.
What I have done so far:
app.post('/pdf',function(req, res) {
pdf.create(html, options).toFile('./businesscard.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res);
});
});
Is this possible using html-pdf? Any help will be greatly appreciated.
Unfortunately, html-pdf module can't handle the dynamic data. You can take a look at the phantomjs which does the screen capture.
In fact, html-pdf module uses "phantomjs" at background. However, it uses the small feature of phantomjs.
You can check dynamic-html-pdf
Just follow the steps:
Install using this command npm install dynamic-html-pdf --save
Create html template
Create pdf with below code:
var fs = require('fs');
var pdf = require('dynamic-html-pdf');
var html = fs.readFileSync('template.html', 'utf8');
pdf.registerHelper('ifCond', function (v1, v2, options) {
if (v1 === v2) {
return options.fn(this);
}
return options.inverse(this);
})
var options = {
format: "A3",
orientation: "portrait",
border: "10mm"
};
//Your dynamic data
var users = [
{
name: 'aaa',
age: 24,
dob: '1/1/1991'
},
{
name: 'bbb',
age: 25,
dob: '1/1/1995'
},
{
name: 'ccc',
age: 24,
dob: '1/1/1994'
}
];
var document = {
type: 'buffer', // 'file' or 'buffer'
template: html,
context: {
users: users
},
path: "./output.pdf" // it is not required if type is buffer
};
pdf.create(document, options)
.then(res => {
console.log(res)
})
.catch(error => {
console.error(error)
});
I was finding solution for the same and got around one.
https://medium.com/free-code-camp/how-to-generate-dynamic-pdfs-using-react-and-nodejs-eac9e9cb4dde
you can checkout this work around done in the blog.
He simply called a function that returns an HTML string and he use backticks for dynamic data.

Malformed request when creating billing plan

So I a using the node paypal-rest-sdk module and I'm trying to create a billing plan. Using the documentation here I made this JSON:
const billingPlanAttributes = {
name: 'Subscription',
description: 'Monthly subscription plan',
type: 'INFINITE',
payment_definitions: [{
name: 'Regular monthly infinite payments',
type: 'REGULAR',
frequency_interval: '1',
frequency: 'MONTH',
cycles: '0',
amount: {
currency: 'USD',
amount: '4.99',
},
}],
merchant_preferences: {
cancel_url: 'http://localhost:3000/subscribe/cancel',
return_url: 'http://localhost:3000/subscribe/return',
auto_bill_amount: 'YES',
},
};
But when using the paypal.billingPlan.create(... function I get the error 'MALFORMED_REQUEST', 'Incoming JSON request does not map to API request'. So I guess my JSON is not in the correct format or I'm missing something that is need.
The documentation has a charge_models key but it does not mention that it is required unlike other keys.
If you can point me in the right direction that would be great.
Edit: changed the return url and cancel url to include the full domain but still same error.
There could be more to this, but I noticed one thing wrong with your JSON. Remove commas for items last in a list. After 'amount' and 'merchant_preferences'. JSON is picky.
late answer, I know, but ran in exactly the same issue than you.
In the create function of the billing plan
public function create($apiContext = null, $restCall = null)
{
$payLoad = $this->toJSON();
$json = self::executeCall(
"/v1/payments/billing-plans/",
"POST",
$payLoad,
null,
$apiContext,
$restCall
);
$this->fromJson($json);
return $this;
}
I found out, that the toJSON method always returned false. Why the hell!?!
I did the same as you did and copied the complete sample code into my code. Then it worked as expected. Now I checked, what the difference was in to my code.
I realized, that I used an umlauts (ä,ü,ö) in the name and description of the billing plan. I changed the umlauts to
'ä' => 'ae',
'ö' => 'oe'
'ü' => 'ue'
Then it worked fine! Maybe someone else is running in this issue, too.

Categories

Resources