Print Values from JSON API React Native - javascript

So I am using react with a news api that gives me the news info in JSON. I want to be able to get the various different components of the JSON news such as the author of the title. The object or json or array( I am confused) looks like this:
[{
"status": "ok",
"totalResults": 20,
-"articles": [
-{
-"source": {
"id": "techcrunch",
"name": "TechCrunch"
},
"author": "Catherine Shu",
"title": "After report on “appalling” conditions, Foxconn will investigate plant that makes Amazon devices",
"description": "Foxconn Technology Group says it is investigating a factory it operates that makes Amazon devices, including Kindles, after an in-depth report by advocacy group China Labor Watch criticized its “appalling working conditions,” including excessive hours and ove…",
"url": "https://techcrunch.com/2018/06/10/after-report-on-appalling-conditions-foxconn-will-investigate-plant-that-makes-amazon-devices/",
"urlToImage": "https://techcrunch.com/wp-content/uploads/2018/06/GettyImages-477662146.jpg?w=657",
"publishedAt": "2018-06-11T05:15:08Z"
},
-{
-"source": {
"id": "the-washington-post",
"name": "The Washington Post"
},
"author": null,
"title": "Owners of Detroit's old train station to discuss its future",
"description": "Owners of the vacant, hulking 105-year-old Michigan Central Station are planning to make an announcement about its future.",
"url": "https://www.washingtonpost.com/national/owners-of-detroits-old-train-station-to-discuss-its-future/2018/06/10/cc5f2680-6d2b-11e8-b4d8-eaf78d4c544c_story.html",
"urlToImage": "https://www.washingtonpost.com/resizer/2CjPNwqvXHPS_2RpuRTKY-p3eVo=/1484x0/www.washingtonpost.com/pb/resources/img/twp-social-share.png",
"publishedAt": "2018-06-11T03:59:18Z"
},
-{
-"source": {
"id": null,
"name": "Newsbtc.com"
},
"author": "JP Buntinx",
"title": "Bitcoin Took a Beating but Should be Bouncing Back",
"description": "Bitcoin has taken a serious beating in the last 48 hours with significant drops happening in two legs plunging the price from just above $7,600 to $6,784 at the time of writing according to livecoinwatch.com.",
"url": "https://www.newsbtc.com/2018/06/11/bitcoin-took-beating-bouncing-back/",
"urlToImage": "https://s3.amazonaws.com/main-newsbtc-images/2018/06/11033811/shutterstock_790702930.jpg",
"publishedAt": "2018-06-11T03:45:38Z"
},
-{
-"source": {
"id": null,
"name": "Wgntv.com"
},
"author": "https://www.facebook.com/wgnnews",
"title": "SONIC brings back 'signature' pickle-flavored snow cone slushes",
"description": "OKLAHOMA CITY-- Starting Monday, June 11, SONIC locations will start serving up frozen snow cone slushes made with pickle juice, and other \"signature\" flavors.\r\n\nIn a release, the company says news the signature slush flavor would be returning \"nearly broke t…",
"url": "http://wgntv.com/2018/06/10/sonic-brings-back-signature-pickle-flavored-snow-cone-slushes/",
"urlToImage": "https://tribwgntv.files.wordpress.com/2018/06/pickle.jpg?quality=85&strip=all&w=1200",
"publishedAt": "2018-06-11T03:39:00Z"
},
-{
-"source": {
"id": null,
"name": "Dailycaller.com"
},
"author": null,
"title": "Twitter CEO Caves To Liberal Backlash, Says He Was Wrong To Eat Chick-Fil-A",
"description": "'Please delete this'",
"url": "http://dailycaller.com/2018/06/10/twitter-ceo-chick-fil-a-gay-marriage/",
"urlToImage": "http://cdn01.dailycaller.com/wp-content/uploads/2018/06/Twitter-CEO-Jack-Dorsey-e1528681520236.jpg",
"publishedAt": "2018-06-11T03:16:24Z"
},
-{
-"source": {
"id": null,
"name": "Forbes.com"
},
"author": "Russell Flannery",
"title": "Wuxi Biologics To Open US Plant Amid Tough Trade Talk",
"description": "Investment may involve $60 million",
"url": "https://www.forbes.com/sites/russellflannery/2018/06/10/wuxi-biologics-to-open-u-s-plant-amid-tough-trade-talk/",
"urlToImage": "https://thumbor.forbes.com/thumbor/600x315/https%3A%2F%2Fi.forbesimg.com%2Fmedia%2Fassets%2Fforbes_1200x1200.jpg",
"publishedAt": "2018-06-11T00:54:00Z"
},
-{
-"source": {
"id": "the-washington-post",
"name": "The Washington Post"
},
"author": null,
"title": "Goodbye to net neutrality. Hello to an even-bigger AT&T?",
"description": "Two developments this week could dramatically expand the power of major telecom companies.",
"url": "https://www.washingtonpost.com/business/economy/goodbye-to-net-neutrality-hello-to-an-even-bigger-atandt/2018/06/10/e7c67f56-6cc0-11e8-bf86-a2351b5ece99_story.html",
"urlToImage": "https://www.washingtonpost.com/resizer/8KmT7MObORQyPc-zaJ37y2eo8yM=/1484x0/arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/Q3LQNWTLJAI6RHRYETTJHM4GG4.jpg",
"publishedAt": "2018-06-11T00:26:54Z"
},
-{
-"source": {
"id": null,
"name": "Newsbtc.com"
},
"author": "https://www.facebook.com/profile.php?id=100012831007659",
"title": "Bitcoin (BTC) Price Technical Analysis (June 11, 2018)",
"description": "Yesterday we saw BTC prices literally crashing after shedding more than five percent. It might be a reactionary move after CFTC Bitcoin Futures investigations but what is important is how prices react at key support lines. Those levels stand at $7,000 and $7,…",
"url": "https://www.newsbtc.com/2018/06/11/bitcoin-btc-price-technical-analysis-june-11-2018/",
"urlToImage": "https://s3.amazonaws.com/main-newsbtc-images/2018/06/08073847/bitcoins.jpg",
"publishedAt": "2018-06-11T00:15:37Z"
},
-{
-"source": {
"id": "reuters",
"name": "Reuters"
},
"author": "Shinichi Saoshiro",
"title": "Asia stocks wobble after G7; Trump-Kim summit, central bank meetings eyed",
"description": "Asia stocks shook off initial modest losses and edged up on Monday ahead of an historic U.S.-North Korea summit that investors hope might pave the way to ending a nuclear stand-off on the Korean peninsula.",
"url": "https://www.reuters.com/article/us-global-markets/asia-stocks-wobble-after-g7-trump-kim-summit-central-bank-meetings-eyed-idUSKBN1J7007",
"urlToImage": "https://s2.reutersmedia.net/resources/r/?m=02&d=20180611&t=2&i=1271269745&w=1200&r=LYNXMPEE5A004",
"publishedAt": "2018-06-11T00:09:27Z"
},
-{
-"source": {
"id": "bloomberg",
"name": "Bloomberg"
},
"author": "Catherine Bosley",
"title": "Swiss Reject Plan That Would Have Revolutionized Banking",
"description": "Switzerland dismissed a proposal to radically change the way banks lend money, a victory for the financial establishment including central bank chief Thomas Jordan.",
"url": "https://www.bloomberg.com/news/articles/2018-06-10/swiss-reject-plan-that-would-have-revolutionized-banking-ji9fmz44",
"urlToImage": "https://assets.bwbx.io/images/users/iqjWHBFdfxIU/iI1kN9CmjjT8/v0/1200x839.jpg",
"publishedAt": "2018-06-10T23:01:00Z"
},
-{
-"source": {
"id": "reuters",
"name": "Reuters"
},
"author": "Reuters Editorial",
"title": "Indian billionaire jeweler Nirav Modi flees to UK, claiming political asylum: FT",
"description": "Nirav Modi, the billionaire jeweler at the heart of a more than $2 billion fraud case in India, has fled to the UK, where he is claiming political asylum, the Financial Times reported on Sunday, citing Indian and British officials.",
"url": "https://www.reuters.com/article/us-britain-india-nirav-modi/indian-billionaire-jeweler-nirav-modi-flees-to-uk-claiming-political-asylum-ft-idUSKBN1J610T",
"urlToImage": "https://s3.reutersmedia.net/resources/r/?m=02&d=20180610&t=2&i=1271236652&w=1200&r=LYNXMPEE590XP",
"publishedAt": "2018-06-10T21:35:03Z"
},
-{
-"source": {
"id": "the-wall-street-journal",
"name": "The Wall Street Journal"
},
"author": "Jacob Bunge",
"title": "A Stampede of Meatless Products Overrun Grocery Store Meat Cases",
"description": "Furious cattlemen see the meat section as their turf, a private reserve of steaks and chops with one thing in common—a butchered animal carcass.",
"url": "https://www.wsj.com/articles/a-stampede-of-meatless-products-overrun-grocery-store-meat-cases-1528653236",
"urlToImage": "https://images.wsj.net/im-13667/social",
"publishedAt": "2018-06-10T17:57:15Z"
},
-{
-"source": {
"id": "fortune",
"name": "Fortune"
},
"author": "David Z. Morris",
"title": "Tyson Foods Recalls Frozen Chicken for Possible Plastic Contamination",
"description": "",
"url": "http://fortune.com/2018/06/10/tyson-chicken-recall-plastic/",
"urlToImage": "https://fortunedotcom.files.wordpress.com/2017/06/tyson-chicken-breaded.jpg",
"publishedAt": "2018-06-10T15:35:23Z"
},
-{
-"source": {
"id": "the-verge",
"name": "The Verge"
},
"author": "Elizabeth Lopatto",
"title": "I have a Boring Company Not-A-Flamethrower",
"description": "The flamethrower started as what seemed like a throwaway joke on Twitter, but Elon Musk and The Boring Company did actually make it. I was among the first 1,000 to pick up my very own.",
"url": "https://www.theverge.com/2018/6/10/17445838/boring-company-flamethrower-elon-musk-tweets-party",
"urlToImage": "https://cdn.vox-cdn.com/thumbor/4fUBJXdApyq46NJbbg-dHfMlb_A=/0x0:2040x1068/fit-in/1200x630/cdn.vox-cdn.com/uploads/chorus_asset/file/11510275/llopatto_180609_2658_0068.jpg",
"publishedAt": "2018-06-10T15:09:00Z"
},
-{
-"source": {
"id": "cnbc",
"name": "CNBC"
},
"author": "Jeff Cox",
"title": "The Fed has a surprise in store that could mean an early end to interest rate hikes",
"description": "The Federal Reserve could have a surprise in store for investors next week, even if everyone already knows the central bank is raising interest rates. The policymaking Federal Open Market Committee is expected to announce another change that would signal an e…",
"url": "https://www.cnbc.com/2018/06/08/fed-has-surprise-that-could-mean-early-end-to-interest-rate-hikes.html",
"urlToImage": "https://fm.cnbc.com/applications/cnbc.com/resources/img/editorial/2018/03/21/105080472-RTS1ONSL.1910x1000.jpg",
"publishedAt": "2018-06-10T13:02:17Z"
},
-{
-"source": {
"id": null,
"name": "Latimes.com"
},
"author": "Meg James",
"title": "Brian Roberts has been the force behind Comcast's growth. Now he's in the hunt for Fox",
"description": "Comcast CEO Brian Roberts is determined to bulk up his company — and that might mean scooping up much of Rupert Murdoch's media empire. \"This is very personal for Brian,\" said his longtime lieutenant Steve Burke.",
"url": "http://www.latimes.com/business/hollywood/la-fi-ct-brian-roberts-comcast-20180610-htmlstory.html",
"urlToImage": "http://www.latimes.com/resizer/dDO6-HPJ9ju6TSMYIrp048Gbu4M=/1200x0/arc-anglerfish-arc2-prod-tronc.s3.amazonaws.com/public/5OIJLZ662BCJ7BBHFTHEWL2PFM.jpg",
"publishedAt": "2018-06-10T12:01:13Z"
},
-{
-"source": {
"id": null,
"name": "Fool.com"
},
"author": "Keith Speights",
"title": "3 Investing Tips From Warren Buffett That You Shouldn't Ignore",
"description": "Great investing advice from one of the greatest investors of all time.",
"url": "https://www.fool.com/investing/2018/06/10/3-investing-tips-from-warren-buffett-that-you-shou.aspx",
"urlToImage": "https://g.foolcdn.com/image/?url=https%3A%2F%2Fg.foolcdn.com%2Feditorial%2Fimages%2F484681%2Fwarren-buffett-tmf-photo-2.jpg&h=630&w=1200&op=resize",
"publishedAt": "2018-06-10T10:32:25Z"
},
-{
-"source": {
"id": null,
"name": "Shropshirestar.com"
},
"author": null,
"title": "G7 members sign joint communique despite US trade tensions",
"description": "Canadian PM Justin Trudeau said the seven leaders had reached agreement on ‘consensus language’.",
"url": "https://www.shropshirestar.com/news/world-news/2018/06/09/g7-members-sign-joint-communique-despite-us-trade-tensions/",
"urlToImage": "https://www.shropshirestar.com/resizer/0Kp-727irloUzDQ7S4rsHNpQnfA=/1200x0/filters:quality(100)/https%3a%2f%2farc-anglerfish-arc2-prod-shropshirestar-mna.s3.amazonaws.com%2fpublic%2fCGU7SHMC7VHA3FBBZ6OPW755KU.jpg",
"publishedAt": "2018-06-09T22:59:13Z"
},
-{
-"source": {
"id": "the-new-york-times",
"name": "The New York Times"
},
"author": "https://www.nytimes.com/by/cade-metz",
"title": "Mark Zuckerberg, Elon Musk and the Feud Over Killer Robots",
"description": "As the tech moguls disagree over the risks presented by something that doesn’t exist yet, all of Silicon Valley is learning about unintended consequences of A.I.",
"url": "https://www.nytimes.com/2018/06/09/technology/elon-musk-mark-zuckerberg-artificial-intelligence.html",
"urlToImage": "https://static01.nyt.com/images/2018/06/10/business/10MUSK/10MUSK-facebookJumbo.gif",
"publishedAt": "2018-06-09T09:00:15Z"
},
-{
-"source": {
"id": "cbs-news",
"name": "CBS News"
},
"author": "AP",
"title": "Kia recalls more than 500000 vehicles -- air bag may not inflate",
"description": "U.S. safety regulators says four people were killed and others injured following front-end crashes",
"url": "https://www.cbsnews.com/news/kia-recalls-more-than-500000-vehicles-air-bag-may-not-inflate/",
"urlToImage": "https://cbsnews1.cbsistatic.com/hub/i/r/2016/06/17/43ec7b9a-f7a8-40a3-9c58-d6c1d92d56de/thumbnail/1200x630/6e37f23635d706b05ceca3838187cb97/gettyimages-451098743.jpg",
"publishedAt": "2018-06-08T17:29:00Z"
}
]
}]
When I do <Text>{this.state.articles}</Text> (which is the variable with the info idk if it is an object or array I am so confused). It gives me the error
Objects are not valid as a React child( found: object with keys {source, author, title... }
I have no idea how to manipulate that giant amount of information. If you could please tell me how to get the title, author and that separate information or direct me to a tutorial that can help me I would be very happy.
Thank you,
The Troubled Programmer

this.state.articles is an array and it not convertible to string
but if want have list of news
you should use flatlist for easily working with data
<FlatList
showsVerticalScrollIndicator={false}
style={{width: 75 * vw, }}
data={this.state.articles}
ListEmptyComponent={this.renderEmpty}
scrollEventThrottle={16}
removeClippedSubviews={true}
renderItem={({item}) =>
<ItemView
keyExtractor={this._keyExtractor}
title={item.title}
description={item.description}
url={item.url}
}
/>
and you should define ItemView in other place and import it for more info https://facebook.github.io/react-native/docs/flatlist.html

As shown in the API, articles will have a list of individual article which is a type of object. It has keys of author,title,description and so on.
When you put <Text>{this.state.articles}</Text>, it means you are throwing an array into a Text Component, which is the reason why you are getting the error.
Since articles is an array of objects, what you can instead do is <Text>{this.state.articles[0].author}</Text> for author and so on.

Related

i can't figure out how to put json response into html element [duplicate]

This question already has answers here:
how to return response to REST api in node js
(2 answers)
How to render node js data in html template?
(1 answer)
How to send HTML as a response in REST?
(1 answer)
Closed 2 years ago.
I wrote this bit of code, and the response comes when I make the api call but I can't figure out why it doesn't show up in the html page.
I really don't know what to do at this point because the page loads but the text doesn't show up in the page
<!DOCTYPE html>
<html>
<head>
<title>IN THE NEWS</title>
<link rel="stylesheet" href="api.css">
<meta charset="utf-8" lang="eng">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div class="sports section">
<h1>SPORTS</h1>
<P class="sport"></P>
</div>
</body>
</html>
const NewsAPI = require('newsapi');
const newsapi = new NewsAPI('API_KEY');
let sports = document.querySelector(".sport").innerHTML;
newsapi.v2.topHeadlines({
category: 'sports',
language: 'en',
country: 'us'
}).then(res =>{
let val = res.articles[0];
sports = val;
})
.catch(rej=>{
console.log(rej);
})
this is the information gotten from the api call
{
source: { id: null, name: 'New York Times' },
author: 'Tariq Panja',
title: 'Manchester City’s Champions League Ban Is Overturned - The New York Times',
description: 'The club, one of the world’s richest teams, had faced a two-year exile from Europe’s top soccer competition for breaking cost-control rules. It had long denied wrongdoing.',
url: 'https://www.nytimes.com/2020/07/13/sports/soccer/manchester-city-champions-league.html',
urlToImage: 'https://static01.nyt.com/images/2020/07/13/sports/13mancity-trophy/13mancity-trophy-facebookJumbo.jpg',
publishedAt: '2020-07-13T08:51:00Z',
content: 'Still, the rules had not stopped City from winning everything but the Champions League title, the crown its owners covet the most. It has another chance to win it in August, when the Champions League… [+1751 chars]'
}
You are reassigning variable, You are not appending data into the DOM.
Replace
sports = val;
With
document.querySelector(".sport").innerHTML = val;
IF the api had a CORS version then you could do this
const res = { "status": "ok", "totalResults": 10, "articles": [ { "source": { "id": "bbc-news", "name": "BBC News" }, "author": "BBC News", "title": "Coronavirus: Llamas provide key to immune therapy", "description": "Llamas' specially evolved small antibodies are the basis for a coronavirus treatment breakthrough.", "url": "http://www.bbc.co.uk/news/science-environment-53369103", "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/EE07/production/_113353906_llamas.jpg", "publishedAt": "2020-07-13T11:20:20Z", "content": "Image copyrightUniversity of ReadingImage caption\r\n Llamas and alpacas have evolved antibodies that scientists 're-engineer' in the lab\r\nAs Fifi the llama munches on grass on a pasture in Reading, he… [+2831 chars]" }, { "source": { "id": "bbc-news", "name": "BBC News" }, "author": "BBC News", "title": "China slaps sanctions on Rubio and Cruz", "description": "The move comes after the US sanctions Chinese officials for Beijing's actions in Xinjiang.", "url": "http://www.bbc.co.uk/news/world-asia-china-53387331", "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/41C3/production/_113353861_rubio-cruz.jpg", "publishedAt": "2020-07-13T10:59:52Z", "content": "Image copyrightReuters / GettyImage caption\r\n Marco Rubio and Ted Cruz are prominent figures in the US Republican party\r\nChina has announced sanctions on top Republicans after the US imposed sanction… [+3122 chars]" }, { "source": { "id": "bbc-news", "name": "BBC News" }, "author": "BBC Sport", "title": "Manchester City overturn two-year ban from European competition on appeal to Cas", "description": "Manchester City successfully overturn their two-year ban from European club competitions.", "url": "http://www.bbc.co.uk/sport/football/53387306", "urlToImage": "https://ichef.bbci.co.uk/onesport/cps/624/cpsprodpb/13590/production/_97584297_breaking_news.png", "publishedAt": "2020-07-13T08:45:57Z", "content": "Manchester City have successfully overturned their two-year ban from European club competitions.\r\nThe Court of Arbitration for Sport (Cas) announced the club were cleared of \"disguising equity funds … [+702 chars]" }, { "source": { "id": "bbc-news", "name": "BBC News" }, "author": "BBC News", "title": "Nelson Mandela's daughter Zindzi dies", "description": "The youngest daughter of South Africa's first black president dies aged 59.", "url": "http://www.bbc.co.uk/news/world-africa-53387667", "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/12CD7/production/_113351077_gettyimages-465640143-002.jpg", "publishedAt": "2020-07-13T07:27:35Z", "content": "Image copyrightGetty Images\r\nZindzi Mandela, the daughter of South Africa's anti-apartheid icons Nelson Mandela and Winnie Madikizela-Mandela, has died, public broadcaster SABC has reported.\r\nShe die… [+518 chars]" }, { "source": { "id": "bbc-news", "name": "BBC News" }, "author": "BBC News", "title": "Actress Kelly Preston, John Travolta's wife, dies", "description": "The US actress after a \"two-year battle with breast cancer\", Travolta said.", "url": "http://www.bbc.co.uk/news/entertainment-arts-53387236", "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/11431/production/_113350707_mediaitem113350706.jpg", "publishedAt": "2020-07-13T06:25:14Z", "content": "Image copyrightAFPImage caption\r\n Travolta and Preston were married for more than 20 years\r\nKelly Preston, actress and wife of John Travolta, has died aged 57.\r\nTravolta posted on Instagram to say Pr… [+1073 chars]" }, { "source": { "id": "bbc-news", "name": "BBC News" }, "author": "BBC News", "title": "Coronavirus updates: Global record for daily virus cases, says WHO", "description": "More than 230,000 cases were confirmed on Sunday - mostly in the Americas and South East Asia.", "url": "http://www.bbc.co.uk/news/live/world-53386093", "urlToImage": "https://m.files.bbci.co.uk/modules/bbc-morph-news-waf-page-meta/4.1.3/bbc_news_logo.png", "publishedAt": "2020-07-13T04:22:22.9453632Z", "content": "Amitabh Bachchan, 77, has starred in hundreds of filmsImage caption: Amitabh Bachchan, 77, has starred in hundreds of films\r\nIndian megastars don't come bigger than the Bachchans, a family considered… [+1062 chars]" }, { "source": { "id": "bbc-news", "name": "BBC News" }, "author": "BBC News", "title": "US federal execution set to go ahead after 17 years", "description": "The execution of convicted murderer Daniel Lewis Lee had been blocked on Friday by a federal judge.", "url": "http://www.bbc.co.uk/news/world-us-canada-53385642", "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/170BA/production/_113349349_mediaitem113349348.jpg", "publishedAt": "2020-07-13T00:44:48Z", "content": "Image copyrightAFPImage caption\r\n Lee killed a family of three before dumping their bodies in a lake\r\nThe first federal execution in the United States for more than 17 years is set to go ahead in Ind… [+2178 chars]" }, { "source": { "id": "bbc-news", "name": "BBC News" }, "author": "BBC News", "title": "Working from home burnout", "description": "A personal trainer, an advertising agency worker and a musician share their experiences of burnout.", "url": "http://www.bbc.co.uk/news/uk-53352234", "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/E467/production/_113317485_p08kbdvh.jpg", "publishedAt": "2020-07-12T23:02:58Z", "content": null }, { "source": { "id": "bbc-news", "name": "BBC News" }, "author": "BBC News", "title": "Duda ahead by tiny margin in Polish election - exit poll", "description": "Conservative President Andrzej Duda leads by a tiny margin against Warsaw mayor, exit poll suggests.", "url": "http://www.bbc.co.uk/news/world-europe-53385021", "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/148B2/production/_111764148_breaking-promo.png", "publishedAt": "2020-07-12T19:16:56Z", "content": "Poland's conservative president Andrzej Duda leads by tiny margin in run-off against Warsaw mayor, exit poll suggests.\r\nThis breaking news story is being updated and more details will be published sh… [+203 chars]" }, { "source": { "id": "bbc-news", "name": "BBC News" }, "author": "BBC News", "title": "Florida breaks record for daily coronavirus infections", "description": "A 24-hour tally of 15,299 new cases eclipses the worst daily rates seen in New York in April.", "url": "http://www.bbc.co.uk/news/world-us-canada-53382540", "urlToImage": "https://ichef.bbci.co.uk/news/1024/branded_news/5DA6/production/_113347932_mediaitem113347931.jpg", "publishedAt": "2020-07-12T19:05:16Z", "content": "Image copyrightEPAImage caption\r\n Intensive care units at many Florida hospitals are reaching capacity\r\nFlorida has registered a state record of 15,299 new coronavirus cases in 24 hours - around a qu… [+1842 chars]" } ] };
document.querySelector(".sport").innerHTML = res.articles.map(
art => `<h3 class="title">${art.title}</h3><p class="description">${art.description}</p><p class="author">${art.author}</p><hr/>`
).join("")
<div class="sports section">
<h1>SPORTS</h1>
<div class="sport"></div>
</div>
NOTE that code ONLY works if the API allows your to access it from JAVASCRIPT, and it does not look like it does
https://newsapi.org/docs/client-libraries
We have libraries for the following languages:
Node.js
Ruby
Python
PHP coming soon
Java coming soon
C#
So I recommend you simply use the node as an API proxy and do something like
const NewsAPI = require('newsapi');
const newsapi = new NewsAPI('API_KEY');
newsapi.v2.topHeadlines({ category: 'sports', language: 'en', country: 'us' })
.then(result => res.send(result))
.catch(rej=>{ console.log(rej); })
Alternatively look into EJS
let sports = document.querySelector(".sport").innerHTML;
newsapi.v2.topHeadlines({
category: 'sports',
language: 'en',
country: 'us'
}).then(res =>{
let val = res.articles[0];
sports = val;
})
What you are doing here is assigning a value of innerHTML to a variable sports, and that is not working as you might expect. sports only contains its value, but not reference, which means that changing the value of sports doesnt change the value of innerHTML.
What you can to do is to assign the sports element to variable sports and then assign the incoming API value to its innerHTML:
let sports = document.querySelector(".sport");
newsapi.v2.topHeadlines({
category: 'sports',
language: 'en',
country: 'us'
}).then(res =>{
let val = res.articles[0];
sports.innerHTML = val;
})

How to Call Array Through API and Push to New Array

I am trying to figure out the proper syntax to push a set of array values to a new array after making an API call. I am trying to combine 2 paths from one API call into a single array to use for an image slider for a product page on an eCommerce site. Here's what I have so far. I need help with the second path and push to array. Any input would be appreciated!
JavaScript
$.getJSON("item-data.json", function(results) {
$.each(results.CatalogEntryView, function(index, item) {
var slideshowArray = [];
//the first path - this works
slideshowArray.push(item.Images[0].PrimaryImage[0].image)
//the second path
$.each(item.Images[0].AlternateImages[0].image, function(k, v) {
slideshowArray.push(v);
});
//used to verify the successful array push
console.log(slideshowArray.length);
});
});
JSON
{
"CatalogEntryView": [
{
"CustomerReview": [
{
"Con": [
{
"RatableAttributes": [
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "4"
},
{
"description": "quality",
"name": "QUALITY",
"value": "1"
},
{
"description": "value",
"name": "VALUE",
"value": "1"
}
],
"datePosted": "Mon Mar 11 13:13:55 UTC 2013",
"overallRating": "1",
"review": "Less than 2 months after purchase it completely stopped working. First it wouldn't detect the pitcher when trying to blend a significant amount, a couple weeks later it wouldn't detect the single serve cup. ",
"reviewKey": "b326b0d6-e6ae-4ec5-8080-720f0ad741af",
"screenName": "New York",
"title": "Very unhappy"
}
],
"ConsolidatedRatableAttributes": [
{
"description": "Quality",
"name": "QUALITY",
"value": "4"
},
{
"description": "Easy to Use",
"name": "EASY_TO_USE",
"value": "4.5"
},
{
"description": "Value",
"name": "VALUE",
"value": "3.5"
}
],
"Pro": [
{
"RatableAttributes": [
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "5"
},
{
"description": "quality",
"name": "QUALITY",
"value": "5"
},
{
"description": "value",
"name": "VALUE",
"value": "5"
}
],
"datePosted": "Thu Apr 18 19:42:19 UTC 2013",
"overallRating": "5",
"review": "This blender works amazingly, and blends within seconds. The single serve cups also work really well for smoothies or protein shakes!",
"reviewKey": "d602bcdf-53be-4769-94da-3b3fd2517d21",
"screenName": "Eric",
"title": "Fantastic Blender"
}
],
"Reviews": [
{
"RatableAttributes": [
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "4"
},
{
"description": "quality",
"name": "QUALITY",
"value": "1"
},
{
"description": "value",
"name": "VALUE",
"value": "1"
}
],
"city": "NYC",
"customerId": "110657105",
"datePosted": "Mon Mar 11 13:13:55 UTC 2013",
"helpfulVotes": "39",
"overallRating": "1",
"review": "Less than 2 months after purchase it completely stopped working. First it wouldn't detect the pitcher when trying to blend a significant amount, a couple weeks later it wouldn't detect the single serve cup. ",
"reviewKey": "b326b0d6-e6ae-4ec5-8080-720f0ad741af",
"screenName": "New York",
"state": "NY",
"title": "Very unhappy",
"totalComments": "0",
"totalVotes": "52"
},
{
"Comments": [
{
"city": "",
"commentKey": "CommentKey:ffcefb66-381a-4985-b869-9fcfdd26e7cc",
"commentText": "Separating the men from the boys, separating the amateurs from the professionals when it comes to blenders, when you revealed to us that, -It doesn't pulverize seeds-.I really need a good blender, but there is No way that I would buy this blender now. Thank you so much, Jon",
"postedDate": "Thu Oct 10 04:17:50 UTC 2013",
"screenName": "JON",
"userKey": "118863321",
"userTier": "Trusted"
}
],
"RatableAttributes": [
{
"description": "quality",
"name": "QUALITY",
"value": "2"
},
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "3"
},
{
"description": "value",
"name": "VALUE",
"value": "2"
}
],
"city": "Idaho Falls",
"customerId": "116317693",
"datePosted": "Sun Sep 01 03:18:11 UTC 2013",
"helpfulVotes": "16",
"overallRating": "2",
"review": "This blender is not superior to other smoothie blenders, It doesn't pulverize seeds and leaves green smoothies chunky with a lot of pulp. The single serve concept is amazing, however, my single serve cup began to break right from the start. The prongs became chipped because of the difficulty of screwing it in and out of the base. It won't blend for more than a minute without smelling like burned rubber. While the single serve seemed to blend more smoothly, it didn't hold much, especially when adding ice. I was very disappointed and so I returned it,",
"reviewKey": "399853f3-4451-40a8-bcd6-bda2d814d9f4",
"screenName": "London",
"state": "ID",
"title": "Very Disappointed",
"totalComments": "1",
"totalVotes": "21"
},
{
"RatableAttributes": [
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "5"
},
{
"description": "quality",
"name": "QUALITY",
"value": "5"
},
{
"description": "value",
"name": "VALUE",
"value": "5"
}
],
"city": "Oakland",
"customerId": "100025104",
"datePosted": "Thu Apr 18 19:42:19 UTC 2013",
"helpfulVotes": "10",
"overallRating": "5",
"review": "This blender works amazingly, and blends within seconds. The single serve cups also work really well for smoothies or protein shakes!",
"reviewKey": "d602bcdf-53be-4769-94da-3b3fd2517d21",
"screenName": "Eric",
"state": "CA",
"title": "Fantastic Blender",
"totalComments": "0",
"totalVotes": "10"
},
{
"RatableAttributes": [
{
"description": "quality",
"name": "QUALITY",
"value": "5"
},
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "5"
},
{
"description": "value",
"name": "VALUE",
"value": "5"
}
],
"city": "Cambridge",
"customerId": "172227",
"datePosted": "Sat Jan 18 01:20:36 UTC 2014",
"helpfulVotes": "9",
"overallRating": "5",
"review": "I am blown away by this blender. It obliterates ice and frozen fruit - and blends fresh fruits to smooth perfection. It even makes quick work of fresh ginger and tough greens. I did a ton of research before settling on the Ninja. This was a splurge for me - and I spent the extra money to get the single serve cups, thinking I'd take my smoothie to work every morning. But my husband is totally hooked on smoothies now too, so the big pitcher is getting regular use. Tried it out for margaritas tonight... half a lime, half a lemon, half an orange with tequila, honey and ice... unbelievably good. Haven't tried it for soup or sauce yet, but can hardly wait.\n\nI'm impressed by features such as the suction cup feet, the snap-seal lid, and the sensor that prevents the machine from being turned on without the top in place. It cleans up nicely too. \n\nBottom line: I can't stop raving about this thing and have recommended it to all my friends and family.",
"reviewKey": "d8e9ac59-6c3a-47be-8b87-f912715ccd18",
"screenName": "E",
"state": "MA",
"title": "Couldn't be happier",
"totalComments": "0",
"totalVotes": "9"
},
{
"Comments": [
{
"city": "",
"commentKey": "CommentKey:a5b92fc8-ec2a-4772-b4ea-3cf4d473015b",
"commentText": "THANK YOU, THANK YOU!!!!! YOU JUST GAVE ME THE BEST REASON TO -- NOT BUY -- THIS THING ! THANK YOU, JON",
"postedDate": "Thu Oct 10 03:44:47 UTC 2013",
"screenName": "JON",
"userKey": "118863321",
"userTier": "Trusted"
}
],
"RatableAttributes": [
{
"description": "quality",
"name": "QUALITY",
"value": "1"
},
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "1"
},
{
"description": "value",
"name": "VALUE",
"value": "1"
}
],
"city": "new york",
"customerId": "116426870",
"datePosted": "Thu Jun 06 04:49:37 UTC 2013",
"helpfulVotes": "38",
"overallRating": "1",
"review": " Upon using this blender it turns out that the food gets into a deep hole at the bottom of the blade assembly , which fits on top of the rotating spindle, which cannot be cleaned. No amount of rinsing or dish washer washing can get to it. A special thin and long brush would be required. Such food deposits can quickly become a place for bacteria growth and accumulate soap from dishwasher etc. A radical design change and going back to the drawing board is required, which Ninja would be unwilling to do. Very poor and harmful product",
"reviewKey": "49add669-1256-4894-9fce-9e0464342887",
"screenName": "gourmet",
"state": "NY",
"title": "bacteria hazard",
"totalComments": "1",
"totalVotes": "69"
},
{
"RatableAttributes": [
{
"description": "quality",
"name": "QUALITY",
"value": "5"
},
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "5"
},
{
"description": "value",
"name": "VALUE",
"value": "5"
}
],
"city": "Wilmington ",
"customerId": "115016455",
"datePosted": "Sun Mar 16 13:54:36 UTC 2014",
"helpfulVotes": "5",
"overallRating": "5",
"review": "Right out of the box I love this thing. You have to read the instructions: it indicates you must pulse several times THEN blend in order to get the smooth consistency. I'm going now to google soups to make. I'll add on to my review once I've tried more stuff. I know some folks had problems, I can say with total confidence that Ninja backs up what they make. I have a vacuum, steamer and iron and I broke the vacuum and they still fixed it for free. Easy peasy. Be sure to register your purchase. Peace. ",
"reviewKey": "bf2283a9-37a1-46e2-b9b4-3edb757d5375",
"screenName": "Sandra",
"state": "DE",
"title": "Great Blender",
"totalComments": "0",
"totalVotes": "5"
},
{
"RatableAttributes": [
{
"description": "quality",
"name": "QUALITY",
"value": "5"
},
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "5"
},
{
"description": "value",
"name": "VALUE",
"value": "5"
}
],
"city": "Tucson",
"customerId": "119946555",
"datePosted": "Thu Jan 30 18:50:22 UTC 2014",
"helpfulVotes": "6",
"overallRating": "5",
"review": "My daughter received this Ninja blender and she absolutely loves it. My grandson has Autisim and has very sensitive taste buds. With the Ninja my daughter is able to puree his homemade soups, & refried beans. Life is a little easier for my daughter & him. She is in heaven. \n",
"reviewKey": "7c7ef8c0-e227-45a5-86cd-c29adeb0bd2a",
"screenName": "Flora",
"state": "AZ",
"title": "Ninja Blender",
"totalComments": "0",
"totalVotes": "7"
},
{
"RatableAttributes": [
{
"description": "quality",
"name": "QUALITY",
"value": "4"
},
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "5"
},
{
"description": "value",
"name": "VALUE",
"value": "5"
}
],
"city": "Minneapolis",
"customerId": "109690154",
"datePosted": "Sun Jan 12 17:41:43 UTC 2014",
"helpfulVotes": "4",
"overallRating": "5",
"review": "I have to assume that the negative reviewers received an unfortunate "lemon" blender... that, or they didn't read the instruction manual, because I love my Ninja and definitely recommend it.\n\nI've had this blender for over a year and it still works as wonderfully as the day I bought it. I use it primarily for making smoothies, everything from green monsters to peanut butter protein shakes to frozen fruit & yogurt smoothies with chia seeds on top.\n\nIt's like having Jamba Juice in my kitchen, but without the long line of snap-chatting teenagers.\n\nI frequently use the to-go cups to blend and take with me in the car. If you are in the camp lamenting that it doesn't hold enough, you probably also expect that once blended, it will be as full as you originally (over)stuffed it.\n\nRespect the max fill line, people, or use the full-size blender if you are going for NYC Big Gulp size.\n\nI will say, that if you are looking to seriously juice, this is not the blender for you. \n\nIt might take a little experimentation to get the right ratio of liquid to solid\/frozen for a perfectly smooth blend, but once you figure out what works for you, it's easy!",
"reviewKey": "9e0322d2-256e-46a5-80dc-b4468e58359b",
"screenName": "Kari",
"state": "MN",
"title": "Love this blender!",
"totalComments": "0",
"totalVotes": "4"
},
{
"RatableAttributes": [
{
"description": "quality",
"name": "QUALITY",
"value": "5"
},
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "5"
},
{
"description": "value",
"name": "VALUE",
"value": "5"
}
],
"city": "Houston",
"customerId": "116412794",
"datePosted": "Wed Jun 05 14:26:21 UTC 2013",
"helpfulVotes": "5",
"overallRating": "5",
"review": "[...]\nAll the parts are well made and good quality. The only thing that seems a little flimsy would be the drinking tops for the single serve cups, but those don't even matter because all you are doing is drinking from the tops. All the rest of the machine is top notch.\n\nThis blender is powerful, quiet and very easy to clean. \n\n[...]\nYou will not regret buying this machine. ",
"reviewKey": "4cc67e87-6754-4cab-8eb7-fb3bd738c16c",
"screenName": "Te-Ann",
"state": "TX",
"title": "LOVE LOVE LOVE!!!!",
"totalComments": "0",
"totalVotes": "6"
},
{
"RatableAttributes": [
{
"description": "quality",
"name": "QUALITY",
"value": "5"
},
{
"description": "easy_to_use",
"name": "EASY_TO_USE",
"value": "5"
},
{
"description": "value",
"name": "VALUE",
"value": "4"
}
],
"city": "CENTREVILLE",
"customerId": "102170259",
"datePosted": "Thu Jan 30 05:33:15 UTC 2014",
"helpfulVotes": "3",
"overallRating": "5",
"review": "I'm not sure why there are so many negative reviews about this blender on Target's website, but it's a great blender. The first blender I've own that actually crushes the ice completely! Perfect for shakes!",
"reviewKey": "3e810dba-638f-4146-aee8-190a741d86d5",
"screenName": "SL",
"state": "VA",
"title": "Fantastic blender!!",
"totalComments": "0",
"totalVotes": "3"
}
],
"consolidatedOverallRating": "4",
"totalPages": "2",
"totalReviews": "14"
}
],
"DPCI": "072-04-1840",
"Images": [
{
"AlternateImages": [
{
"image": "http:\/\/target.scene7.com\/is\/image\/Target\/14263758_Alt01"
},
{
"image": "http:\/\/target.scene7.com\/is\/image\/Target\/14263758_Alt02"
},
{
"image": "http:\/\/target.scene7.com\/is\/image\/Target\/14263758_Alt03"
},
{
"image": "http:\/\/target.scene7.com\/is\/image\/Target\/14263758_Alt04"
},
{
"image": "http:\/\/target.scene7.com\/is\/image\/Target\/14263758_Alt05"
},
{
"image": "http:\/\/target.scene7.com\/is\/image\/Target\/14263758_Alt06"
},
{
"image": "http:\/\/target.scene7.com\/is\/image\/Target\/14263758_Alt07"
}
],
"PrimaryImage": [
{
"image": "http:\/\/target.scene7.com\/is\/image\/Target\/14263758"
}
],
"imageCount": "8",
"source": "internal"
}
],
"ItemDescription": [
{
"features": [
"<strong>Wattage Output:<\/strong> 1100 Watts",
"<strong>Number of Speeds:<\/strong> 3 ",
"<strong>Capacity (volume):<\/strong> 72.0 Oz.",
"<strong>Appliance Capabilities:<\/strong> Blends",
"<strong>Includes:<\/strong> Travel Lid",
"<strong>Material:<\/strong> Plastic",
"<strong>Finish:<\/strong> Painted",
"<strong>Metal Finish:<\/strong> Chrome",
"<strong>Safety and Security Features:<\/strong> Non-Slip Base",
"<strong>Care and Cleaning:<\/strong> Easy-To-Clean, Dishwasher Safe Parts"
]
}
],
"Offers": [
{
"OfferPrice": [
{
"currencyCode": "USD",
"formattedPriceValue": "$139.99",
"priceQualifier": "Online Price",
"priceValue": "13999"
}
]
}
],
"POBoxProhibited": "We regret that this item cannot be shipped to PO Boxes.",
"PackageDimension": [
{
"name": "length",
"unit": "IN",
"value": "17.4"
},
{
"name": "width",
"unit": "IN",
"value": "12.4"
},
{
"name": "height",
"unit": "IN",
"value": "9.9"
},
{
"name": "weight",
"unit": "LB",
"value": "10.85"
}
],
"Promotions": [
{
"Description": [
{
"legalDisclaimer": "Offer available online only. Offer applies to purchases of $50 or more of eligible items across all categories. Look for the "SPEND $50: SHIPS FREE" logo on eligible items. Some exclusions apply. Items that are not eligible are subject to shipping charges. $50 purchase is based on eligible merchandise subtotal. Items that are not eligible, GiftCards, e-GiftCards, gift wrap, tax and shipping and handling charges will not be included in determining merchandise subtotal. Offer valid for orders shipping within the 48 contiguous states, as well as APO\/FPO and for Standard and To the Door shipping methods only. Not valid on previous orders.",
"shortDescription": "SPEND $50, GET FREE SHIPPING"
}
],
"endDate": "2014-05-25 06:59:00.001",
"promotionIdentifier": "10736506",
"promotionType": "Buy catalog entries from category X, get shipping at a fixed price",
"startDate": "2014-05-18 07:00:00.001"
},
{
"Description": [
{
"legalDisclaimer": "Receive a $25 gift card when you buy a Ninja Professional Blender with single serve blending cups or a Ninja MEGA Kitchen System. Not valid on previous orders. On your order summary, the item subtotal will reflect the price of the qualifying item plus the amount of the free gift card, followed by a discount given for the amount of the free gift card. Your price on the order summary will be the price of the qualifying item (the total charges for the qualifying item and gift card). Your account will actually be charged the amount of the qualifying item reduced by the amount of the gift card, and a separate charge for the amount of the gift card. The gift card will be sent to the same address as your order and will ship separately. If you want to return the item you purchased to a Target Store, you may either keep the gift card and just return the qualifying item (you will be refunded the amount of the qualifying item reduced by the amount of the gift card), or you can return the qualifying item and the gift card for a full refund using the online receipt. If you return the item you purchased by mail, keep the gift card; you will be refunded the amount of the qualifying item reduced by the amount of the gift card. Offer expires 05\/24\/14 at 11:59pm PST.",
"shortDescription": "$25 gift card with purchase of a select Ninja Blender"
}
],
"endDate": "2014-05-25 06:59:00.001",
"promotionIdentifier": "10730501",
"promotionType": "Multiple Items Free Gift",
"startDate": "2014-05-11 07:00:00.001"
}
],
"ReturnPolicy": [
{
"ReturnPolicyDetails": [
{
"guestMessage": "View our return policy",
"policyDays": "100",
"user": "Regular Guest"
},
{
"guestMessage": "View our return policy",
"policyDays": "120",
"user": "Best Guest"
}
],
"legalCopy": "refund\/exchange policy<br\/><br\/><p style=\"font-size:13px;\">Most unopened items in new condition returned within 90 days will receive a refund or exchange. Some items have a modified return policy that is less than 90 days. Those items will either show a \"return by\" date or \"return within\" day range under the item on your receipt or packing slip and in the \"Item details, shipping\" tab if purchased on Target.com. Items that are opened or damaged or do not have a packing slip or receipt may be denied a refund or exchange. All bundled items must be returned with all components for a full refund. Bundle components may not all have the same return policy; please check your packing slip for details. Some items, such as gift cards, digital items are never returnable. <br \/><br \/>See the <a href=\"http:\/\/www.target.com\/HelpContent?help=\/sites\/html\/TargetOnline\/help\/returns_and_refunds\/returns_and_refunds.html\">Target return policy<\/a> for complete information.<\/p><br\/>"
}
],
"UPC": "622356532099",
"applyCouponLink": "false",
"buyable": "true",
"callOutMsg": "FREE $25 GIFT CARD",
"catEntryId": "205273068",
"classId": "04",
"department": "072",
"eligibleFor": "ADD_TO_CART",
"inventoryCode": "0",
"inventoryStatus": "Online",
"itemId": "1840",
"itemType": "ItemBean",
"manufacturer": "Euro Pro",
"manufacturerPartNumber": "BL660",
"packageQuantity": "null ",
"partNumber": "14263758",
"purchasingChannel": "Sold Online + in Stores",
"purchasingChannelCode": "0",
"shortDescription": "For the first time EVER - you get the same professional performance power in the Single Serve as well as the XL 72 oz pitcher! The Ninja\u2122 Professional Blender with Single Serve Blending Cups allow you to crush ice into snow, blend whole fruits and vegetables into nutritious beverages, and create resort style blended drinks! Full size blender performance now in individual cups.",
"title": "Ninja\u2122 Professional Blender with Single Serve Blending Cups",
"webclass": "Small Appliances"
}
]
}

Lodash append object from another object without replacement

How can I append value to an object from another object without replacement?
I am trying to append a value from ObjectA to ObjectB as the name of a child object.
This is ObjectA.
As you can tell, ObjectA has 4 child object and each associates with a uid.
This is ObjectB
So I'm trying to map the uid of each child from ObjectA to ObjectB.
This is what the ideal code would look like
Object.keys(ObjectA).forEach(
(key) => _.assign(ObjectB, {'Product 07': true})
)
I tried to inject each ObjectB iteration to the source placeholder ES6 string interpolation but it would fail, like so.
Object.keys(ObjectA).forEach(
(key) => _.assign(ObjectB, {`${basketObject[key].uid}`: true})
)
Source(JSON)
Please use this code to convert Object of objects to Object of arrays with _.mapValues to generate uid from Object name
var ObjectA = _.mapValues(data, (val, index) => {
return { ...val, index }
})
{
"Product": {
"Product 01": {
"approved": true,
"brand": "MANGO",
"category": "Woman",
"color": "Black,Bright Pink",
"description": "Rounded neck Chain detail Slit detail Zip fastening on the back section Inner lining · Side length 117.0 cm · Back length 135.5 cm These measures have been calculated for a S size.",
"imageURL": "https://s11.postimg.org/612lpusf7/73025590_80.jpg",
"name": "Chain Collar Dress",
"price": 499,
"purchasedUser": {
"mgzQBxjF9NNVACh18ID1xDPtrwH2": true
},
"size": "S,M,L,XL"
},
"Product 02": {
"approved": true,
"brand": "MANGO",
"category": "Man",
"color": "Grey",
"description": "Modern coat that suits every man",
"imageURL": "https://s4.postimg.org/vub6umtlp/73079700_99.jpg",
"name": "Tailored wool-blend overcoat",
"price": 899,
"purchasedUser": {
"mgzQBxjF9NNVACh18ID1xDPtrwH2": true
},
"size": "S,M,L,XL"
},
"Product 03": {
"approved": true,
"brand": "MANGO",
"category": "Kid",
"color": "Dark Navy, Offwhite, Light Pink,Medium Heather Grey",
"description": "Cotton fabric Spots print Rounded neck Short sleeve Embroidered Mango logo Decorated with sequins",
"imageURL": "https://s16.postimg.org/xkpg8qypx/73003605_56.jpg",
"name": "Logo cotton t-shirt",
"price": 29.9,
"purchasedUser": {
"mgzQBxjF9NNVACh18ID1xDPtrwH2": true
},
"size": "3-4 years,5-6 years, 7-8 years, 9-10 years, 11-12 years, 13-14 years"
},
"Product 04": {
"approved": true,
"brand": "UNIQLO",
"category": "Woman",
"color": "Red, Natural, Navy",
"description": "This comfortable women's shirt features the distinctive soft, warm, fuzzy feel of brushed 100% cotton flannel material. It looks great as a shirt or light outer layer, and the slightly loose cut gives it a relaxed style. The classic casual plaid design is available in a variety of colors.",
"imageURL": "https://s11.postimg.org/48sak0lmr/69_180861.jpg",
"name": "Flannel Check Long Sleeve Shirt",
"price": 79.9,
"size": "S,M,L,XL"
},
"Product 05": {
"approved": true,
"brand": "UNIQLO",
"category": "Kid",
"color": "Offwhite",
"description": "Star Wars™ A long time ago in a galaxy far, far awayLong after the Jedi Knights have perished, young Luke Skywalker has a fateful encounter with Princess Leia, a leader of the Rebel forces. Luke and Leia fight alongside Han Solo, Chewbacca, R2-D2 and C-3PO against the evil forces of Darth Vader to help restore peace in the galaxy. starwars.com © & ™ Lucasfilm Ltd. MATERIAL100% Cotton CAREMachine wash cold",
"imageURL": "https://s21.postimg.org/xdojmkx1z/01_185878.jpg",
"name": "BOYS STAR WARS Short Sleeve Graphic T-Shirt",
"price": 39.9,
"size": "110cm,120cm,130cm,140cm,150cm"
},
"Product 06": {
"approved": true,
"brand": "UNIQLO",
"category": "Man",
"color": "White,Dark Grey, Navy",
"description": "This amazing men's polo is made from next-generation, high-tech DRY-EX material. It dries sweat incredibly quickly to keep you feeling smooth, dry, and comfortable. The soft, cotton-like texture and cut allow for easy movement and combined, offer for superb comfort. In a fashionable striped pattern, perfect for warm-weather casual looks. MATERIAL[08Dark Gray] Body: 96% Polyester, 4% Nylon/ Rib: 100% Polyester [Other Colors] 100% Polyester CARE[08Dark Gray] Machine wash cold, gentle cycle [Other Colors] Machine wash cold",
"imageURL": "https://s11.postimg.org/bvm6i0ujn/00_169374.jpg",
"name": "MEN Dry EX Short Sleeve Polo Shirt",
"price": 99.9,
"size": "S,M,L,XL"
},
"Product 07": {
"brand": "FILANTO",
"category": "Woman",
"color": "Black",
"description": "Dress to impress this festive season with our must-have dresses. Our favourite piece for for creating effortlessly chic and glamorous look comes in the form of this delicate lace number. A form-fitting silhouette hugs and flatter your curves beautifully while its minimalist design makes it easy to dress it up or down.",
"imageURL": "https://s15.postimg.org/5qqq9496j/r1_top_fl20131894_002_a_btm_a_fl20131894.jpg",
"name": "Casual Long Dress",
"price": 59.9,
"size": "S,M,L,XL"
},
"Product 08": {
"brand": "HOTSHOTS",
"category": "Kid",
"color": "Off White",
"description": "Update her dress collection with this beautiful printed piece. Offering a short-sleeve design, round neckline and keyhole back button fastening. This dress also showcases a vibrant butterfly print motif. Sweet and demure, all this piece needs is a pair of flats to complete the look.",
"imageURL": "https://s16.postimg.org/ocebpd3h1/ho20129717_002_e_ho20129717.jpg",
"name": "Casual Short Dress Knit",
"price": 29.9,
"size": "4-5,6-7,8-9,10-11"
},
"Product 09": {
"approved": true,
"brand": "PADINI",
"category": "Man",
"color": "White",
"description": "Steeped in a solid white wash, this classic Oxford shirt gets a modern tweak with the addition of stripes across the body. It also features the iconic shirt collar, along with a chest pocket, buttoned cuffs and raised placket. This is the ultimate piece for curating both casual and formal looks.",
"imageURL": "https://s11.postimg.org/cvmbgxg2r/r1_top_pd20131998_003_b_btm_pd20131965_002_b_pd2.jpg",
"name": " Casual Long Sleeve Shirt",
"price": 89,
"size": "XS,S,M,L"
},
"Product 10": {
"brand": "PONEY",
"category": "Kid",
"color": "Navy",
"description": "This navy polo shirt designed with knight prints is Poney's new wardrobe classic. Made from 100% Cotton Fully Comb and Single Jersey. Features a neat polo collar, brown buttons, neckline lining in contrast fabric and leather patches.",
"imageURL": "https://s17.postimg.org/bcpbfwrcf/6j6a5351_2_1_1.jpg",
"name": "KNIGHT POLO SHIRT",
"price": 119,
"size": "7-8,9-10,11-12"
},
"Product 11": {
"brand": "PONEY",
"category": "Kid",
"color": "Navy",
"description": "This beautiful daisy print blouse with contrast sleeves is perfect for your best friend's birthday party. Pair with our \"Poney Daisy Print Jeans\" for a chic contemporary look or our \"Poney Tutu Skirt\" for a classic party look.",
"imageURL": "https://s12.postimg.org/la1o7vtm5/6j6a5327_1.jpg",
"name": "DAISY PRINT BLOUSE",
"price": 76,
"size": "1-2,2-3,3-4,4-5,5-6"
},
"Product 12": {
"brand": "GAMESTERS",
"category": "Kid",
"color": "Grey",
"description": "Ensure your little one is clothed in comfort and style with this super-cool and adorable jogger shorts from Gamester. Complete with an allover repetitive print, elasticated-drawstring waist, two front side pockets and one back pocket. Complement this shorts with any printed tee to complete his look.",
"imageURL": "https://s14.postimg.org/tz3xvg3z5/gm20130687_002_e_gm20130687.jpg",
"name": "Casual Knit Shorts",
"price": 29.9,
"size": "6-7"
}
}
}
it should work
_.mapValues(ObjectA, (val) => {
ObjectB[val.uid] = true;
})
You can use reduce to map your objects to another object;
var objects = [ // Your objects, this is just dummy data
{ uuid: 'Product 01', approved: true },
{ uuid: 'Product 02', approved: true },
{ uuid: 'Product 03', approved: true }
]
var items = objects.reduce(function (prev, current) {
prev[current.uuid] = current.approved;
return prev;
}, {});

Nested For Loop Pass Variable

I need to get foreach value of "site[id]" take "purchase[id]". I use object keys because the data varies and i have no knowledge of the ids. What is the correct and most efficient way to achieve this?
var data = {
"user_id": null,
"created_at": "2016-11-09T05:52:42.279Z",
"total_prices": {
"final_price": "$173.11",
"shipping_price": "$13.18"
},
"notes": null,
"used_profiles": null,
"sites": {
"56c6cce830bb1f28f8000022": {
"info": {
"url": "a1supplements.com",
"name": "A1 Supplements",
"logo": "https://px.twotap.com/unsafe/https%3A//core.twotap.com/system/sites/logos/56c6/cce8/30bb/1f28/f800/0022/small/56c6cce830bb1f28f8000022.png%3F1478498606243"
},
"prices": {
"shipping_price": "$6.95",
"final_price": "$86.90"
},
"details": {
"shipping_estimate": "2-5 Days"
},
"order_id": "fake_confirm_order_id",
"products": {
"458aa2317f92043a0713b37e03b47b2d": {
"original_url": "https://www.a1supplements.com/labrada-iso-leanpro",
"clean_url": "https://www.a1supplements.com/labrada-iso-leanpro",
"category_attributes": null,
"categories": [
"Everything Else"
],
"status": "done",
"required_fields": {
"quantity": {
"data": [{
"input_type": "text",
"input_name": "INPUT"
}]
},
"flavor": {
"data": [{
"input_type": "select-one",
"input_name": "SELECT"
}]
},
"size": {
"data": [{
"input_type": "select-one",
"input_name": "SELECT"
}]
}
},
"discounted_price": null,
"pickup_support": false,
"url": "https://www.a1supplements.com/labrada-iso-leanpro",
"required_field_values": {
"size": [{
"weight": "2267.985122017599",
"value": "5 Lbs.",
"text": "5 Lbs.",
"price": "$79.95",
"image": "https://www.a1supplements.com/media/catalog/product/cache/1/image/317x/9df78eab33525d08d6e5fb8d27136e95/2/3/23523.jpg",
"extra_info": "",
"dep": {
"flavor": [{
"weight": "2267.985122017599",
"value": "Chocolate",
"text": "Chocolate",
"price": "$79.95",
"image": "https://www.a1supplements.com/media/catalog/product/cache/1/image/317x/9df78eab33525d08d6e5fb8d27136e95/2/3/23523.jpg",
"extra_info": ""
}, {
"weight": "2267.985122017599",
"value": "Vanilla",
"text": "Vanilla",
"price": "$79.95",
"image": "https://www.a1supplements.com/media/catalog/product/cache/1/image/317x/9df78eab33525d08d6e5fb8d27136e95/2/3/23523.jpg",
"extra_info": ""
}]
}
}]
},
"required_field_names": [
"size",
"flavor",
"quantity"
],
"weight": "2267.985122017599",
"site_categories": [
"Home",
"Protein",
"Whey Protein Powder",
"Whey Protein Isolate"
],
"description": "100% Premium Whey Protein Isolate!\n<strong>Made with 100% PURE WHEY PROTEIN ISOLATE</strong> as the sole protein source, ISO LeanPro contains ZERO carbs, sugar, lactose and gluten—no junk, fillers, or cheap blends.<br><br><strong>ISO LeanPro is not a blend</strong> containing whey protein concentrate, peptides, or other proteins. You get only 100% pure whey protein isolate as the source of protein.<br><br><strong>ISO LeanPro is sugar-free,</strong> and carb-free, so it&apos;s perfect for dieting.<br><br><strong>ISO LeanPro is lactose-free,</strong> so there is no bloating, gas, or indigestion associated with cheap proteins.<br><br><strong>ISO LeanPro is gluten-free,</strong> perfect for individuals who must avoid gluten because they suffer from gluten sensitivities.<br><br><strong>ISO LeanPro is perfect for athletes,</strong> bodybuilders, and fitness enthusiasts who demand the purest, highest quality protein available on the market.<br><br><strong>ISO LeanPro has a BV of 159,</strong> making it more bio-available than any other protein source. The most accurate way of testing the bioavailability of proteins is with the BV (Biological Value) method which measures actual nitrogen retention in humans.<br><br><strong>ISO LeanPro 100% Whey Protein Isolate</strong> is an excellent source of all the essential amino acids and is extremely rich in the branched chain amino acids (BCAAs), leucine, isoleucine, and valine.<br><br><strong>Branched chain amino acids</strong> make up one-third of muscle protein and are important to athletes because training increases the body&apos;s demand for them. An adequate supply of BCAAs in the blood is insurance against loss of muscle size and strength. ISO LeanPro is also high in glutamine, which accounts for approximately 60% of all free amino acids in the body.<br><br><strong>Labrada Nutrition CEO and IFBB Pro Bodybuilding</strong> Hall of Famer Lee Labrada says, "ISO LeanPro is a very pure protein powder designed for elite athletes and bodybuilders who want the very best money can buy. ISO LeanPro is very quickly absorbed and utilized, so it&apos;s perfect for use right before and after training, to put the body into an anabolic state."<br><br> <strong>FDA</strong>: These statements have not been evaluated by the Food and Drug Administration. This product is not intended to diagnose, treat, cure, or prevent any disease.<br><br><i>Shop our 100% secure server and get your supplements at the lowest prices everyday! NOBODY beats our overall price.</i><br> <div> <h3>Supplement Facts</h3> <strong>Supplement Facts:</strong><br><br>Serving Size: 1 Scoop (32g)<br>Servings Per Container: 71<br><br>Amount Per Serving <br>Calories 115 <br>Calories from Fat 9 <br>Total Fat 1 g 2%<br>Saturated Fat 0 g 0%<br>Trans Fat 0 g <br>Cholesterol 0 mg 0%<br>Sodium 150 mg 6%<br>Potassium 150 mg 5%<br>Total Carbohydrate 1 g 0%<br>Dietary Fiber 0 g 0%<br>Sugars 0 g <br>Protein 25 g 50%<br>Vitamin A 0%<br>Vitamin C 0%<br>Calcium 13%<br>Iron 0%<br><br>Ingredients: Cross-Flow Micro Ultrafiltered Whey Protein Isolate, Natural & Artificial Flavors, Dutched Cocoa, Cellulose Gum, Salt, Acesulfame Potassium, Sucralose.<br><br>NOTE: Supplement facts and ingredients may vary by flavor.<br><br>Allergen Information: Contains Milk, Soy.<br><br> </div> <div> <h3>Directions</h3> <p>Directions: Glass – Fill glass with 4–6 oz. of water or your favorite beverage. Add 1 scoop of ISO LeanPro, and mix with a spoon. Shaker – Fill shaker with 4–6 oz. of water or your favorite beverage. Add 1 scoop of ISO LeanPro. Cover and shake. Blender – Fill blender with 4–6 oz. of water or your favorite beverage. For a creamy ice cream flavor, add a handful of ice cubes. Add 1 scoop of ISO LeanPro. Cover and blend.<br><br>Note: Manufacturers continually change product specifications. While we try our best to keep product descriptions up to date, they do not necessarily reflect the latest information available from the manufacturer. We are not responsible for incorrect or outdated product descriptions and/or images. <br> <br></p> </div>",
"image": "https://www.a1supplements.com/media/catalog/product/cache/1/image/317x/9df78eab33525d08d6e5fb8d27136e95/2/3/23523.jpg",
"original_price": "$129.99",
"price": "$79.95",
"title": "Labrada ISO LeanPro",
"input_fields": {
"quantity": "1",
"flavor": "Vanilla",
"size": "5 Lbs."
}
}
},
"status": "done"
},
"5679041130bb1f37570026f5": {
"info": {
"url": "bodybuilding.com",
"name": "Bodybuilding",
"logo": "https://px.twotap.com/unsafe/https%3A//core.twotap.com/system/sites/logos/5679/0411/30bb/1f37/5700/26f5/small/5679041130bb1f37570026f5.png%3F1478589601755"
},
"prices": {
"final_price": "$86.21",
"shipping_price": "$6.23"
},
"details": {},
"failed_to_add_to_cart": null,
"order_id": "fake_confirm_order_id",
"products": {
"b634b0cc8751b14b54031c5c94d47de4": {
"original_url": "http://www.bodybuilding.com/store/zoller/Zantrex-3.html",
"clean_url": "http://www.bodybuilding.com/store/zoller/Zantrex-3.html",
"weight": "1000",
"category_attributes": null,
"categories": [
"Everything Else"
],
"status": "done",
"required_fields": {
"option 1": {
"data": [{
"input_type": "select-one",
"input_name": "SELECT"
}]
}
},
"discounted_price": null,
"original_price": null,
"pickup_support": false,
"url": "http://www.bodybuilding.com/store/zoller/Zantrex-3.html",
"required_field_values": {
"option 1": [{
"weight": "",
"value": "56 Capsules",
"text": "56 Capsules",
"price": "$24.99",
"image": "https://store.bbcomcdn.com/images/store/skuimage/sku_ZL008/image_skuZL008_largeImage_X_70_white.jpg",
"extra_info": "clearance, clearance"
}]
},
"required_field_names": [
"option 1"
],
"extra_info": "clearance clearance",
"site_categories": [
"Zantrex-3 Fat Burner"
],
"description": "Famous High-Energy Component!*\nHigh Energy Fat Burning Support!*",
"image": "https://store.bbcomcdn.com/images/store/prodimage/prod_35283/image_35283_original_X_450_white.jpg",
"price": "$24.99",
"title": "Zantrex-3 Fat Burner",
"input_fields": {
"quantity": "1",
"option 1": "56 Capsules"
}
},
"ba621a59cac993a24789d390efb741fc": {
"title": "Hydroxycut CLA Elite Next Gen",
"price": "$54.99",
"image": "https://store.bbcomcdn.com/images/store/prodimage/prod_prod3990044/image_prodprod3990044_largeImage_X_450_white.jpg",
"description": "Advanced, Scientifically-Tested Weight Loss Driver*\nSupplies 95% Cla Plus L-Carnitine And Garcinia Indica",
"site_categories": [
"Hydroxycut CLA Elite Next Gen"
],
"extra_info": "Buy 1 Get 1 Free Buy 1 Get 1 Free",
"required_field_names": [
"option 1"
],
"required_field_values": {
"option 1": [{
"extra_info": "Buy 1 Get 1 Free, Buy 1 Get 1 Free",
"image": "https://store.bbcomcdn.com/images/store/skuimage/sku_MT4240203/image_skuMT4240203_largeImage_X_70_white.jpg",
"price": "$54.99",
"text": "100 Raspberry Flavored Softgels",
"value": "100 Raspberry Flavored Softgels",
"weight": ""
}]
},
"url": "http://www.bodybuilding.com/store/muscletech/hydroxycut-next-gen-cla-elite.html",
"pickup_support": false,
"original_price": null,
"discounted_price": null,
"required_fields": {
"option 1": {
"data": [{
"input_name": "SELECT",
"input_type": "select-one"
}]
}
},
"status": "done",
"categories": [
"Everything Else"
],
"category_attributes": null,
"weight": "1000",
"clean_url": "http://www.bodybuilding.com/store/muscletech/hydroxycut-next-gen-cla-elite.html",
"original_url": "http://www.bodybuilding.com/store/muscletech/hydroxycut-next-gen-cla-elite.html",
"input_fields": {
"quantity": "1",
"option 1": "100 Raspberry Flavored Softgels"
}
}
},
"status": "done"
}
},
"message": "done",
"final_message": "Hi! We've confirmed 2 orders:\n\nA1 Supplements total $86.90 vs our initial estimate of $85.90 (shipping $6.95 vs estimated $5.95).\n* products: Labrada ISO LeanPro.\n* delivery estimate: 2-5 Days.\n* store order number: fake_confirm_order_id.\n\nBodybuilding total $86.21 vs our initial estimate of $91.41.\n* products: Zantrex-3 Fat Burner; Hydroxycut CLA Elite Next Gen.\n* delivery estimate: 2-5 Days.\n* store order number: fake_confirm_order_id.\n\nTotal $173.11."
};
var initial_index = Object.keys(data.sites)[0];
var product_index = Object.keys(data.sites[initial_index].products)[0];
var jj = (data.sites);
for (var key in jj) {
if (jj.hasOwnProperty(key)) {
console.log(key + ": " + jj[key]);
var ee = (data.sites[jj].products);
for (var key in ee) {
if (ee.hasOwnProperty(key)) {
console.log(key + ": " + ee[key]);
}
}
}
}
When executing the code above I receive the following error because the variable from the first loop isn't getting passed to the second loop.
VM1172:301 Uncaught TypeError: Cannot read property 'products' of undefined(…)
A few things:
var ee = (data.sites[jj].products); won't work because jj is an object, not the key
You've declared key twice, so the inner loop won't be able to read the outer one simply because they have the same name.
It's generally better to use Object.keys(...).forEach(...) in these sorts of loops as long as you don't need legacy browser support. The parameter of the forEach call will be a function that will be executed once per key in the object. More info here.

Query with join between documents

I would like to create a view in CouchDb which contains some fields from multiple linked documents.
My documents are something like this:
/*Products:*/
{
"_id": "Products:ABC",
"doctype": "Products",
"productCode": "ABC",
"description": "The best product you ever seen",
"category_id": "Categories:1",
"brand_id": "Brands:52"
},
{
"_id": "Products:DEF",
"doctype": "Products",
"productCode": "DEF",
"description": "DEFinitely a good product",
"category_id": "Categories:2",
"brand_id": "Brands:53"
},
/*Categories*/
{
"_id": "Categories:1",
"categoryID": "1",
"description": "Awesome products"
},
{
"_id": "Categories:2",
"categoryID": "2",
"description": "Wonderful supplies"
},
/*Brands*/
{
"_id": "Brands:52",
"brandID": "52",
"description": "Best Items"
},
{
"_id": "Brands:53",
"brandID": "53",
"description": "Great Gadgets"
},
I would like to have a result like this:
/*View results: */
{
"id": "Products:ABC",
"key": "Products:ABC",
"value": {
"productCode": "ABC",
"description": "The best product you ever seen",
"category": {
"categoryID": "1",
"description": "Awesome products"
},
"brand": {
"brandID": "52",
"description": "Best Items"
}
}
},
{
"id": "Products:DEF",
"key": "Products:DEF",
"value": {
"productCode": "DEF",
"description": "DEFinitely a good product",
"category": {
"categoryID": "2",
"description": "Wonderful supplies"
},
"brand": {
"brandID": "53",
"description": "Great Gadgets"
}
}
},
The goal is to have a result that is a join between the three documents. Is it possibile?
As you can imagine I come from the SQL world, so maybe I am designing the database terribly wrong, so any advice on how to change the documents structure is welcome!
Thanks in advance!
Francesco
There are two ways to do this:
Use the query() API and linked documents (search the page for "linked documents")
Use the relational-pouch plugin
The advantage of the relational-pouch plugin is that, under the hood, it is faster than linked documents because it doesn't rely on building up a map/reduce index. The advantage of linked documents is that it is the more traditional way of solving this problem in CouchDB, and it doesn't rely on an extra plugin. Choose whichever one you like. :)
Edit: re-reading your question, I see you want to join 3 different document types together. Currently that is not possible with linked documents (you can only "join" two types), whereas it is possible with relational-pouch. So I guess that makes the decision easy. :)

Categories

Resources