Parsing a JSON array when its the first response - javascript

I am a bit stuck parsing a JSON array when it is the only thing returned in a JSON response.
I know how to parse an array when it is a sub record of a json response but not as the only response.
For example, i know how to do data.streams.array[0].item for example but when there is no 'streams' part of that i am not sure what to do (basically it goes straight to array[0]
Sample code of what i have tried below
$( document ).ready(function() {
console.log( "ready to explore" );
$("#getMessage").click(function(){
$("ul").empty();
$.getJSON("https://api.planningalerts.org.au/applications.js?key=<<KEY>>&postcode=2000", function(json){
var test2 = JSON.stringify(json);
alert(test2);
var test = json.address;
alert(test);
Sample json resposne i am trying to parse (remembering it goes straight to array)
[{
"application": {
"id": 609706,
"council_reference": "1-3879101556",
"address": "\"Harbour Plaza\" Lot 5, 25-29 Dixon Street, Haymarket 2000",
"description": "Triple 8 Hotel - Liquor licence transfer",
"info_url": "http://www.ilga.nsw.gov.au/liquor/application-noticeboard",
"comment_url": "mailto:liquorapplications#olgr.nsw.gov.au?subject=Application%20Number:%201-3879101556",
"lat": -33.877797,
"lng": 151.203659,
"date_scraped": "2016-01-06T01:01:59.000Z",
"date_received": "2016-01-05",
"on_notice_from": null,
"on_notice_to": "2016-02-04",
"no_alerted": 178,
"authority": {
"full_name": "NSW Independent Liquor and Gaming Authority"
}
}
}, {
"application": {
"id": 609709,
"council_reference": "1-3879170112",
"address": "World Square L 10 680 George St, Sydney 2000",
"description": "Sydney Chinese New Year 2016 - Chinese Film Festival 15/02/2016 - Limited licence - special event",
"info_url": "http://www.ilga.nsw.gov.au/liquor/application-noticeboard",
"comment_url": "mailto:liquorapplications#olgr.nsw.gov.au?subject=Application%20Number:%201-3879170112",
"lat": -33.8772162,
"lng": 151.2068193,
"date_scraped": "2016-01-06T01:01:59.000Z",
"date_received": "2016-01-05",
"on_notice_from": null,
"on_notice_to": "2016-01-19",
"no_alerted": 182,
"authority": {
"full_name": "NSW Independent Liquor and Gaming Authority"
}
}
}]
Any help really appreciated :)
Cheers

First off, you don't have to parse anything; jQuery will parse it before giving it to your callback. (For that reason, json probably isn't a great argument name; perhaps data or response or applications.)
To access its data, you do so just like any other JavaScript array (because that's what it is). For instance, the first entry is an object with a property called application which refers to an object with a property called address with the value "\"Harbour Plaza\" Lot 5, 25-29 Dixon Street, Haymarket 2000". So:
console.log(json[0].application.address); // "Harbour Plaza" Lot 5, 25-29 Dixon Street, Haymarket 2000
There's also a second entry, whose address is "World Square L 10 680 George St, Sydney 2000", so:
console.log(json[1].application.address); // World Square L 10 680 George St, Sydney 2000
Or loop through the array, for example:
json.forEach(function(entry) {
console.log(entry.application.address);
});
shows
"Harbour Plaza" Lot 5, 25-29 Dixon Street, Haymarket 2000
World Square L 10 680 George St, Sydney 2000

Related

Unable to get the value from object

I'm creating an app in React and trying to get data from object via function for rendering.
However, I'm getting errors and I banged my head on this for many hours but failed.
Help will be really appreciated.
I'm getting the following error:
TypeError: Cannot read property 'title' of undefined
I'm pasting the code below (Please see my comments inline):
render() {
return (
<div aria-live="assertive">
<h2>Headlines</h2>
<ul>
{
Object.values(this.state.news).map((item) => {
console.log(item[0].title); //Doesn't work however:
console.log(item[0]); //This works and prints the object to the console properly.
})
}
</ul>
</div>
}
And here is the object structure:
{
"id": 36174,
"user_id": 1,
"feed_id": 6,
"status": "unread",
"hash": "e953071e47ce854a03508542f4f4eab471a386fd5fa200600486663c56240965",
"title": "SC junks plea seeking return of MPLAD funds donated to PM CARES Fund during COVID-19 pandemic",
"url": "https://www.firstpost.com/india/sc-junks-plea-seeking-return-of-mplad-funds-donated-to-pm-cares-fund-during-covid-19-pandemic-9311531.html",
"comments_url": "",
"published_at": "2021-02-16T20:07:56+05:30",
"created_at": "2021-02-16T18:29:32.804004+05:30",
"content": "<p>The Supreme Court Tuesday dismissed a plea seeking direction to the Centre to return Rs 365 crore donated by MPs from MPLADS fund to PM CARES Fund for tackling exigencies emerging from the COVID-19 pandemic.</p><p>A bench of Chief Justice Bobde and Justices AS Bopanna and V Ramasubramanian said it is not inclined to entertain the petition and dismissed it.</p><p>Advocate Dushyant Tiwari, appearing for petitioner Tushar Gupta, said that Rs 365 crore were donated by lawmakers from Members of Parliament Local Area Development Scheme (MPLADS) in the PM CARES Fund, in contravention of the guidelines.</p><p>Tiwari referred the RTI reply to buttress his claims and said that development work was hampered due to the diversion of the funds.</p><p>The plea filed by Gupta sought appropriate direction to the central government to return the entire donated amount in the bank account in which MPLADS funds are transferred every year.</p><p>The scheme's objective is to enable MPs to recommend developmental work "with emphasis on the creation of durable community assets based on the locally felt needs to be taken up in their Constituencies, the plea said.</p><p>It said that right from inception of the scheme, durable assets of national priorities -- drinking water, primary education, public health, sanitation and roads -- are being created.</p><p>It is pertinent to note that in the month of March 2020, various MP's have donated MPLAD Fund for the pandemic and as per information a total number of 339 MP's have contributed a total of Rs 365 crore from their MPLADS to the Central pool for measures towards tackling exigencies in India emerging from the effect of the pandemic, the plea added.</p><p>The petition said that in April 2020 the MPLADS funds were suspended for two financial years -- 2020-2021 and 2021-2022.</p><p>Gupta referred to the RTI reply and said it raised few important questions and doubts related to the donation of the MPLAD Fund for the purpose of COVID-19.</p><p>The plea sought direction to the MPs to re-prioritise the earlier recommended works so that the incomplete work can be completed from the un-utilised amount available with the district authority.</p>",
"author": "Press Trust of India",
"share_code": "",
"starred": false,
"reading_time": 2,
"feed": {
"id": 6,
"user_id": 1,
"feed_url": "https://www.firstpost.com/rss/india.xml",
"site_url": "https://www.firstpost.com/category/india",
"title": "Firstpost India News",
"checked_at": "2021-02-16T18:29:32.331595+05:30",
"next_check_at": "0001-01-01T00:00:00Z",
"etag_header": "",
"last_modified_header": "",
"parsing_error_message": "",
"parsing_error_count": 0,
"scraper_rules": "",
"rewrite_rules": "",
"crawler": false,
"blocklist_rules": "",
"keeplist_rules": "",
"user_agent": "",
"username": "",
"password": "",
"disabled": false,
"ignore_http_cache": false,
"fetch_via_proxy": false,
"category": {
"id": 5,
"title": "India News",
"user_id": 1
},
"icon": {
"feed_id": 6,
"icon_id": 5
}
}
}
So, here I'm unable to identify that if the complete object is being printed out in the console by using the second line (Please refer the code above) then why it is giving the error in first console.log call.
Please help
The corresponding map function is working with only with arrays. U are trying to output normal objects. Just Add
<ul> {title} </ul>
<ul> {feed.title} </ul>

Can you automate adding products from an online store to WooCommerce?

I would like to get all the products from an account on this Dutch webshop (similar to eBay/Amazon) and add them to this WordPress webshop using WooCommerce. I started web development about 2 to 3 weeks ago, and I know the basics of HTML, CSS, JavaScript, Nodejs, and Express. I think I know roughly what to do, that is:
Iterate over all the products per page.
Grab the title, description, category, price, and photo.
Store that information in an array with product objects.
Get access to WooCommerce API.
Iterate over all the products and add them to WooCommerce.
My questions are:
Is this possible?
Can I do it with the languages available to me?
What methods would you use? (e.g. how would you scrape the HTML, is there an easier way than the steps I described, would you do this using code or rather using some automation software, etc.)
This is a big project for me, so any help (on how to start) is welcome!
You are right about the steps and yes that is possible. You can scrape the data with node.js as you know already, my personal preference is python when it comes to data scraping but you can do it in node.js. Node.js has HTML parser and so on. I would suggest you a few things:
Parse the HTML data with a parser to get better access to the elements in order to get the data.
Use some kind of data structure to store the data properly, for example: JSON, XML, CSV...
If getting the data is a long process, get the data first as you may lose all the data while parsing if any section in your parsing system doesn't suit, parse the data afterwards.
I will bring here the code I wrote to get the data from the website you put, it's in python language but I put comments on it so you can get a better understanding about how you can get the data and write in other languages. You can also use split to cut the sections from HTML data, you don't even need to use a parser.
Example:
import requests, json
from bs4 import BeautifulSoup
from pprint import pprint
endpoint = "http://johndevisser.marktplaza.nl/?p=1"
# Send a get request to page to get the html.
data = requests.get(endpoint).content
# Parse the html via BeautifulSoup
page = BeautifulSoup(data)
# Find 'div' elements whose 'itemscope' attributes are 'itemscope'
products = page.find_all("div", {"itemscope": "itemscope"})[1:]
# Create an empty array to store prepared data.
finalProductList = []
# Iterate over the products.
for i in products:
# Create a dictionary object to store data properly.
productData = {}
# Get the title attribute from 'a' element on the current product.
productData["title"] = i.find("a").get("title")
# Get the href attribute from 'a' element on the current product because the real source can be useful in the future.
productData["origin"] = i.find("a").get("href")
# Get the image url from 'img' elements to download images.
productData["imageURL"] = i.find("img").get("src")
# This may look you complicated but it just finds 'span' elements value of 'class' attribute is 'subtext' and get the
# inner text, split into two from ' '(space) to this ['€', '15,00'] and get the right part which is the second part
# in the array which is the price and replace comma with dot to parse in float value.
productData["price"] = float(i.find("span", {"class": "subtext"}).get_text().split(u"\xa0")[1].replace(",", "."))
# Append the data to final data array.
finalProductList.append(productData)
# Get json representation of dictionary.
print(json.dumps(finalProductList))
Output:
[
{
"title": "Sieb Posthuma - Mannetje Jas (Hardcover/Gebonden) Kinderjury",
"origin": "http://www.marktplaza.nl/boeken/kinderboeken/sieb-posthuma-mannetje-jas-hardcover-gebonden-kinderjury-92409632.html",
"imageURL": "http://www.marktplaza.nl/M92409632/1/sieb-posthuma-mannetje-jas-hardcover-gebonden-kinderjury-92409632.jpg",
"price": 12.5
},
{
"title": "Estefhan Meijer - United Wraps Wraps Uit De Hele Wereld",
"origin": "http://www.marktplaza.nl/boeken/kookboeken/estefhan-meijer-united-wraps-wraps-uit-de-hele-wereld-92390218.html",
"imageURL": "http://www.marktplaza.nl/M92390218/1/estefhan-meijer-united-wraps-wraps-uit-de-hele-wereld-92390218.jpg",
"price": 15
},
{
"title": "Daphne Deckers - De Verschrikkelijke Ijstaart (Hardcover/Gebonden)",
"origin": "http://www.marktplaza.nl/boeken/kookboeken/daphne-deckers-de-verschrikkelijke-ijstaart-hardcover-gebonden-92390182.html",
"imageURL": "http://www.marktplaza.nl/M92390182/1/daphne-deckers-de-verschrikkelijke-ijstaart-hardcover-gebonden-92390182.jpg",
"price": 10
},
{
"title": "Adelene Fletcher - Bomen Aquarelleren Van A Tot Z",
"origin": "http://www.marktplaza.nl/boeken/hobby-techniek/adelene-fletcher-bomen-aquarelleren-van-a-tot-z-92390124.html",
"imageURL": "http://www.marktplaza.nl/M92390124/1/adelene-fletcher-bomen-aquarelleren-van-a-tot-z-92390124.jpg",
"price": 12.5
},
{
"title": "Razorlight ‎– America (2 Track CDSingle)",
"origin": "http://www.marktplaza.nl/cd-vinyl/singles/razorlight-america-2-track-cdsingle-92390118.html",
"imageURL": "http://www.marktplaza.nl/M92390118/1/razorlight-america-2-track-cdsingle-92390118.jpg",
"price": 5
},
{
"title": "Twarres ‎– Children (2 Track CDSingle)",
"origin": "http://www.marktplaza.nl/cd-vinyl/singles/twarres-children-2-track-cdsingle-92390078.html",
"imageURL": "http://www.marktplaza.nl/M92390078/1/twarres-children-2-track-cdsingle-92390078.jpg",
"price": 5
},
{
"title": "Tower Of Power ‎– The Very Best Of Tower Of Power - The Warner Years (CD)",
"origin": "http://www.marktplaza.nl/cd-vinyl/pop/tower-of-power-the-very-best-of-tower-of-power-the-warner-years-cd-92389836.html",
"imageURL": "http://www.marktplaza.nl/M92389836/1/tower-of-power-the-very-best-of-tower-of-power-the-warner-years-cd-92389836.jpg",
"price": 10
},
{
"title": "Red Hot Chili Peppers ‎– Dani California (2 Track CDSingle)",
"origin": "http://www.marktplaza.nl/cd-vinyl/singles/red-hot-chili-peppers-dani-california-2-track-cdsingle-92389742.html",
"imageURL": "http://www.marktplaza.nl/M92389742/1/red-hot-chili-peppers-dani-california-2-track-cdsingle-92389742.jpg",
"price": 5
},
{
"title": "Seth Godin - Icarus Deception (Engelstalig)",
"origin": "http://www.marktplaza.nl/boeken/management-en-economie/seth-godin-icarus-deception-engelstalig-92389542.html",
"imageURL": "http://www.marktplaza.nl/M92389542/1/seth-godin-icarus-deception-engelstalig-92389542.jpg",
"price": 12.5
},
{
"title": "Rob Gifford - De Chinese Weg",
"origin": "http://www.marktplaza.nl/boeken/reizen/rob-gifford-de-chinese-weg-92389500.html",
"imageURL": "http://www.marktplaza.nl/M92389500/1/rob-gifford-de-chinese-weg-92389500.jpg",
"price": 12.5
},
{
"title": "Bart Leeuwenburgh - Darwin In Domineesland",
"origin": "http://www.marktplaza.nl/boeken/informatief/bart-leeuwenburgh-darwin-in-domineesland-92386128.html",
"imageURL": "http://www.marktplaza.nl/M92386128/1/bart-leeuwenburgh-darwin-in-domineesland-92386128.jpg",
"price": 12.5
},
{
"title": "Per Olov Enquist - Het Record (Hardcover/Gebonden)",
"origin": "http://www.marktplaza.nl/boeken/romans/per-olov-enquist-het-record-hardcover-gebonden-92386080.html",
"imageURL": "http://www.marktplaza.nl/M92386080/1/per-olov-enquist-het-record-hardcover-gebonden-92386080.jpg",
"price": 10
},
{
"title": "Fred Vargas - Uit De Dood Herrezen (Hardcover/Gebonden) blauw/groene achtergrond",
"origin": "http://www.marktplaza.nl/boeken/romans/fred-vargas-uit-de-dood-herrezen-hardcover-gebonden-blauw-groene-achtergrond-92385368.html",
"imageURL": "http://www.marktplaza.nl/M92385368/1/fred-vargas-uit-de-dood-herrezen-hardcover-gebonden-blauw-groene-achtergrond-92385368.jpg",
"price": 12.5
},
{
"title": "Fred Vargas - De Omgekeerde Man (Hardcover/Gebonden)",
"origin": "http://www.marktplaza.nl/boeken/romans/fred-vargas-de-omgekeerde-man-hardcover-gebonden-92385304.html",
"imageURL": "http://www.marktplaza.nl/M92385304/1/fred-vargas-de-omgekeerde-man-hardcover-gebonden-92385304.jpg",
"price": 15
},
{
"title": "David Sandes - Sergei Bubka's Wondermethode (Hardcover/Gebonden)",
"origin": "http://www.marktplaza.nl/boeken/romans/david-sandes-sergei-bubkas-wondermethode-hardcover-gebonden-92385090.html",
"imageURL": "http://www.marktplaza.nl/M92385090/1/david-sandes-sergei-bubkas-wondermethode-hardcover-gebonden-92385090.jpg",
"price": 10
},
{
"title": "Sjoerd Kuyper - Sjaantje Doet Alsof (Hardcover/Gebonden)",
"origin": "http://www.marktplaza.nl/boeken/kinderboeken/sjoerd-kuyper-sjaantje-doet-alsof-hardcover-gebonden-92384948.html",
"imageURL": "http://www.marktplaza.nl/M92384948/1/sjoerd-kuyper-sjaantje-doet-alsof-hardcover-gebonden-92384948.jpg",
"price": 10
},
{
"title": "Het Piratenschip Klap Open En Bekijk (Hardcover/Gebonden)",
"origin": "http://www.marktplaza.nl/boeken/kinderboeken/het-piratenschip-klap-open-en-bekijk-hardcover-gebonden-92371996.html",
"imageURL": "http://www.marktplaza.nl/M92371996/1/het-piratenschip-klap-open-en-bekijk-hardcover-gebonden-92371996.jpg",
"price": 12.5
},
{
"title": "John Topsell - Draken Trainen En Verzorgen (Hardcover/Gebonden)",
"origin": "http://www.marktplaza.nl/boeken/kinderboeken/john-topsell-draken-trainen-en-verzorgen-hardcover-gebonden-92371928.html",
"imageURL": "http://www.marktplaza.nl/M92371928/1/john-topsell-draken-trainen-en-verzorgen-hardcover-gebonden-92371928.jpg",
"price": 15
}
]

validating location submitted by user

I'm building a web app that calls the mapquest Geocoding API to grab the users lat-long position, and then make a second call to another API to return another set of data. The main issue I am having is when I call the mapquest Geocode API the user can enter any string of characters or made up locations and it returns JSON with data. I need to find a way to prevent this by ensuring the user enters an actual location. Here is the mapquest Geocode API https://developer.mapquest.com/documentation/geocoding-api/address/get/
and I believe my answer lies in here but I am not sure how I would use these to validate the location https://developer.mapquest.com/documentation/geocoding-api/quality-codes/
I've tried setting up a few if statements looking for an X in any of the values for responseJson.results[0].locations[0].geocodeQualityCode
but that still kicked back valid results
this is an example of an acceptable entry that the API returns
{
"info": {
"statuscode": 0,
"copyright": {
"text": "© 2019 MapQuest, Inc.",
"imageUrl": "http://api.mqcdn.com/res/mqlogo.gif",
"imageAltText": "© 2019 MapQuest, Inc."
},
"messages": []
},
"options": {
"maxResults": -1,
"thumbMaps": true,
"ignoreLatLngInput": false
},
"results": [
{
"providedLocation": {
"location": "Lawton, ok"
},
"locations": [
{
"street": "",
"adminArea6": "",
"adminArea6Type": "Neighborhood",
"adminArea5": "Lawton",
"adminArea5Type": "City",
"adminArea4": "Comanche County",
"adminArea4Type": "County",
"adminArea3": "OK",
"adminArea3Type": "State",
"adminArea1": "US",
"adminArea1Type": "Country",
"postalCode": "",
"geocodeQualityCode": "A5XAX",
"geocodeQuality": "CITY",
"dragPoint": false,
"sideOfStreet": "N",
"linkId": "282026294",
"unknownInput": "",
"type": "s",
"latLng": {
"lat": 34.606378,
"lng": -98.396817
},
"displayLatLng": {
"lat": 34.606378,
"lng": -98.396817
},
"mapUrl": "http://www.mapquestapi.com/staticmap/v5/map?key=zkn6RGyTDlLGsN8i8RfEmURf2GozTAkL&type=map&size=225,160&locations=34.606378,-98.396817|marker-sm-50318A-1&scalebar=true&zoom=12&rand=197404762"
}
]
}
]
}
Given the Lawton, ok input, the geocoder returns an A5XAX which means that it found a city (A5) with no address match (the first X) an exact city/state match (A) and not postal code match (the second X).
You can plug the returned quality code into the documentation page for a full explanation with some more detail.
The geocode api is not intended to prevent users from entering any string of characters or made up locations by ensuring the user enters an actual location. If the input isn't random keystrokes, there is probably a city or street name that will be a close match and return something other than an X. So the application will need to decide what position it will accept a no-match in and how many no-matches it will accept. For instance, if you need an exact address match for a delivery, you'll want no X and probably all A or B confidences. If a city is ok, then XAX may be fine. As always, it depends.

Is it possible to get a list of all items in an array of objects that match items in another array?

I'm working on a React project that'll allow me to search through a list of games to help me decide what to play based on what I'm in the mood for, currently I can add games to a JSON file but I'm really struggling with the searching part.
Right now, to add a new game, you'll enter the title, genre(s) and a description of the game. The genre field is a ReduxForm FieldArray object, and I think that's what's giving me the trouble. Here's my current JSON file
{
"games": [
{
"name": "Rainbow Six: Siege",
"genres": [
{
"genre": "tactical"
},
{
"genre": "shooter"
}
],
"description": "tactical team based shooter",
"id": 1
},
{
"name": "Resident Evil 2",
"genres": [
{
"genre": "horror"
},
{
"genre": "survival"
},
{
"genre": "shooter"
}
],
"description": "classic resident evil 2 remake in 2019",
"id": 2
},
{
"name": "Rocket League",
"genres": [
{
"genre": "cars"
},
{
"genre": "competition"
},
{
"genre": "one more game"
}
],
"description": "soccar!",
"id": 3
}
]
}
This is the dummy data I'm using to search:
const searchedGenres = 'horror, shooter';
const searchedList = searchedGenres.split(', ');
let foundGame = [];
Once I get the search working with this data, the plan is to allow me to just type in data on the frontend in one textbox, so "horror, shooter" would be my search term. The result from this search should only return Resident Evil 2, however I'm also receiving Rainbow Six: Siege as a result, even though it's missing one of my requested genres.
searchedList.forEach(searchedGenre => {
this.props.games.map(game => {
if (
game.genres.find(
({ genre }) =>
genre.toLowerCase() ===
searchedGenre.toLowerCase().trim()
) !== undefined
) {
foundGames.push(game);
}
});
});
I understand why I'm getting both Rainbow Six and Resident Evil as a result, because I'm not actually checking that both genres are in the games genres when I add the game to the foundGames array, but I'm completely lost on how I'd go about making sure all of the genres are in a game before I add it.
This would be a bit easier if your genres was a simple array of strings rather than objects, but still you can check pretty succinctly by leveraging some() and every() within filter() (btw filter() is a better choice than map() + push() here)
let games = [{"name": "Rainbow Six: Siege","genres": [{"genre": "tactical"},{"genre": "shooter"}],"description": "tactical team based shooter","id": 1},{"name": "Resident Evil 2","genres": [{"genre": "horror"},{"genre": "survival"},{"genre": "shooter"}],"description": "classic resident evil 2 remake in 2019","id": 2},{"name": "Rocket League","genres": [{"genre": "cars"},{"genre": "competition"},{"genre": "one more game"}],"description": "soccar!","id": 3}]
const searchedGenres = 'horror, shooter';
const searchedList = searchedGenres.split(', ');
let foundGame = games.filter(game => searchedList.every(searchItem => game.genres.some(g => g.genre == searchItem) ))
console.log(foundGame)
The filter condition basically says you want every game in searchedList to match at least one genre in the game. This will make it only return games that match every genre.

Map local .json data in React

I have a local .json file formated below
{
"results": [
{
"id": 1,
"title": "2 bedroom apartment to rent",
"location": "30 South Colonnade London E14 5EZ",
"description": "The building offers a communal lifestyle which consists of a large lounge area with dining room, working space, TV lounge, gym, stylish meeting rooms, free table tennis, free WIFI and a spacious communal roof terrace. Local transport includes Canning Town DLR and Jubilee Line (0.1 miles). Argo Apartments is managed by Grainger plc, one of the UK's leading professional landlords with over 100 years experience.",
"price": "1,800",
"beds": 2,
"bathrooms": 1,
"landlord": "Hamptons International Lettings",
"images": ["image1", "image2"]
},
{
"id": 2,
"title": "2 bedroom flat to rent",
"location": "Textile Building, Chatham Place, Hackney, London, E9",
"description": "SHORT LET - Forming part of the new eagerly awaited Textile Building in Hackney Central E8, this stunning two double bedroom property has been finished to the highest standard, featuring two modern fitted bathrooms (one en-suite), two equal double bedrooms, spacious open plan reception with brand new integrated kitchen, exposed brickwork and communal underground bike storage.",
"price": "2,400",
"beds": 2,
"bathrooms": 1,
"landlord": "Stirling Ackroyd, Hackney",
"images": ["image1", "image2"]
},
{
"id": 3,
"title": "3 bedroom apartment to rent",
"location": "Sixth Floor Tower Building 11 York Road London SE1 7NX",
"description": "A fantastic three bedroom apartment set in this popular development close to Vauxhall and Stockwell tube stations. The apartment is neutrally decorated throughout and is available either furnished or unfurnished. Residents will enjoy the plethora of shops, bars and restaurants and leisure activities in this popular part of London as well as the excellent commuter links towards Central London.",
"price": "2,050",
"beds": 3,
"bathrooms": 2,
"landlord": "Regent Letting and Property Management",
"images": ["image1", "image2"]
}
],
"newResults" : [
{
"id": 4,
"title": "2 bedroom flat to rent",
"location": "Conway Street, Fitzrovia, W1T",
"description": "Complete is delighted to market this newly renovated period property situated on the corner of Fitzroy Square in the heart of Fitzrovia, W1. The property is located on the ground floor and comes with 2 double bedrooms, shower room, open plan living and kitchen area. The kitchen is fully fitted with Siemens appliances and Duravit fittings in the bathroom. This apartment has high ceiling and retains its original period features. Located on the corner of this garden square this development was built in the 18th Century and benefits from being in the heart of vibrant London whilst also being a quiet residential area.",
"price": "1,500",
"beds": 2,
"bathrooms": 1,
"landlord": "Barnard Marcus Lettings",
"images": ["image1", "image2"]
}
]
}
I want to be able to call the relevent information mapped to a component as below
class ResultsLists extends React.Component {
constructor(props) {
super(props)
this.state = {
results: resultsData
}
}
render() {
const results = this.state.results.results.map((result) =>
<li>{result}</li>
);
return (
<div className="rst-List">
<ul className="rst-List_Items">
{results}
</ul>
</div>
)
}
}
I can't seem to get it too work and am getting the error - Objects are not valid as a React child. There seems to be a varying variety as to why this isn't working, wondered whether someone could sanity check.
You're mapping over the results, but then you're putting the whole result object into the JSX.
This is an example of how to map over data:
const someData = [{ name: "Colin" }, { name: "Ricardo" }];
const App = () => {
const temp = someData.map(o => <li>{o.name}</li>);
return (
<div>
<ul>{temp}</ul>
</div>
);
};
Note that we have {o.name} and not just {o}.
Working example here.
So in your case, you need something like:
const results = this.state.results.results.map((result) =>
<li>{result.title}</li>
);

Categories

Resources