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>
);
Related
I want to delete items in an array that include('https://www.agci.org').
I am splitting the array first with ('>') and then using that to search each string with the includes function. I want to delete the ones that include a url and then use the array with the deleted items and set it back to arr[i].authors. Idk why spl = arr[i].authors line isnt working when its still within the if statement/function
for(var i=0, len = arr.length; i < len; i++){
var spl = arr[i].authors[0].split('>');
spl.forEach(function(item){
if(item.includes('https://www.agci.org')){
delete item;
spl = arr[i].authors
}
})
}
for(var i=0, len = arr.length; i < len; i++){
var spl = arr[i].authors[0].split('>');
spl.forEach(function(item){
if(item.includes('https://www.agci.org')){
result = spl.filter(item)
arr[i].authors = result;
}
})
}
my arrays look like this. they are random arrays that i need to sort and filter through
arr = [
{
"post_title": "Food System Impacts of Pests & Pathogens in a Changing Climate",
"authors":
[
"https://www.agci.org/redhen/contact/1520\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Roz_low_res_9_11_cropped.jpg?itok=vDp_RwzD\">https://www.agci.org/redhen/contact/1520\">Rosamond Lee Naylor>Stanford University>William Wrigley Professor of Earth System Science; Founding Director of the Center on Food Security and the Environment; Senior Fellow at the Stanford Woods Institute for the Environment and the Freeman Spogli Institute for International Studies.>https://www.agci.org/redhen/contact/2354\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Battisti.jpg?itok=82GpfOY3\">https://www.agci.org/redhen/contact/2354\">David S Battisti>University of Washington>Tamaki Chair of Atmospheric Sciences >https://www.agci.org/redhen/contact/3091\">https://www.agci.org/sites/default/files/styles/headshot/public/default_images/AGCI_profile_sm.jpg?itok=7Trdel1u\">https://www.agci.org/redhen/contact/3091\">Curtis Deutsch>>>https://www.agci.org/redhen/contact/3092\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Ronald.jpg?itok=Qre04udp\">https://www.agci.org/redhen/contact/3092\">Pamela Ronald>>>https://www.agci.org/redhen/contact/3093\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Tewksbury.jpg?itok=gdBNWssA\">https://www.agci.org/redhen/contact/3093\">Josh Tewksbury>>"
]
},
{
"post_title": "Impacts of Land Use and Land Management on Earth System Evolution, Biogeochemical Cycles, Extremes and Inter-Sectoral Dynamics",
"authors":
[
"https://www.agci.org/redhen/contact/2511\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/CalvinK_0.jpg?itok=rIidxNOX\">https://www.agci.org/redhen/contact/2511\">Kate Calvin>Pacific Northwest National Laboratory>Earth Scientist>https://www.agci.org/redhen/contact/2052\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/13S2_Hurtt.jpg?itok=iQsU00Xe\">https://www.agci.org/redhen/contact/2052\">George Hurtt>University of Maryland>Professor>https://www.agci.org/redhen/contact/2055\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Lawrence_photo.png?itok=qCnfHCfg\">https://www.agci.org/redhen/contact/2055\">David Lawrence>National Center for Atmospheric Research (NCAR)>Senior Scientist "
]
},
{
"post_title": "Advancing the Theory and Practice of Urban Heat Resilience",
"authors":
[
"https://www.agci.org/redhen/contact/3175\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/ladd-keith-sm.jpg?itok=cnW3QjGu\">https://www.agci.org/redhen/contact/3175\">Ladd Keith>University of Arizona>Assistant Professor>https://www.agci.org/redhen/contact/3176\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Dave%20Hondula.jpg?itok=ewI2DCd_\">https://www.agci.org/redhen/contact/3176\">David Hondula>Arizona State University>Senior Sustainability Scientist; Associate Professor; Faculty Affiliate >https://www.agci.org/redhen/contact/3179\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Hunter-Professional-Cropped-291x300.jpg?itok=etdVjEL7\">https://www.agci.org/redhen/contact/3179\">Hunter Jones>National Oceanic and Atmospheric Administration>Climate and Health Projects Manager>https://www.agci.org/redhen/contact/2748\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/sara%20m.jpg?itok=048o8evr\">https://www.agci.org/redhen/contact/2748\">Sara Meerow>Arizona State University>Assistant Professor>https://www.agci.org/redhen/contact/3178\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/v-kelly-turner-600x800.jpg?itok=DikoBPnV\">https://www.agci.org/redhen/contact/3178\">V. Kelly Turner>University of California, Los Angeles>Assistant Professor"
]
},
{
"post_title": "Advancing the Theory and Practice of Urban Heat Resilience",
"authors":
[
"https://www.agci.org/redhen/contact/3175\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/ladd-keith-sm.jpg?itok=cnW3QjGu\">https://www.agci.org/redhen/contact/3175\">Ladd Keith>University of Arizona>Assistant Professor>https://www.agci.org/redhen/contact/3176\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Dave%20Hondula.jpg?itok=ewI2DCd_\">https://www.agci.org/redhen/contact/3176\">David Hondula>Arizona State University>Senior Sustainability Scientist; Associate Professor; Faculty Affiliate >https://www.agci.org/redhen/contact/3179\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Hunter-Professional-Cropped-291x300.jpg?itok=etdVjEL7\">https://www.agci.org/redhen/contact/3179\">Hunter Jones>National Oceanic and Atmospheric Administration>Climate and Health Projects Manager>https://www.agci.org/redhen/contact/2748\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/sara%20m.jpg?itok=048o8evr\">https://www.agci.org/redhen/contact/2748\">Sara Meerow>Arizona State University>Assistant Professor>https://www.agci.org/redhen/contact/3178\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/v-kelly-turner-600x800.jpg?itok=DikoBPnV\">https://www.agci.org/redhen/contact/3178\">V. Kelly Turner>University of California, Los Angeles>Assistant Professor"
]
}
]
I want them to look like this but idk if theres a way to filter the author names because they include the positions as well.
arr = [
{
"post_title": "Advancing the Theory and Practice of Urban Heat Resilience",
"authors": [
Ladd Keith,David Hondula,Hunter Jones,Sara Meerow,V. Kelly Turner"
]
}
]
Possibly just a case for RegExp? Here using String.prototype.match().
const arr = [{ "post_title": "Food System Impacts of Pests & Pathogens in a Changing Climate", "authors": ["https://www.agci.org/redhen/contact/1520\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Roz_low_res_9_11_cropped.jpg?itok=vDp_RwzD\">https://www.agci.org/redhen/contact/1520\">Rosamond Lee Naylor>Stanford University>William Wrigley Professor of Earth System Science; Founding Director of the Center on Food Security and the Environment; Senior Fellow at the Stanford Woods Institute for the Environment and the Freeman Spogli Institute for International Studies.>https://www.agci.org/redhen/contact/2354\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Battisti.jpg?itok=82GpfOY3\">https://www.agci.org/redhen/contact/2354\">David S Battisti>University of Washington>Tamaki Chair of Atmospheric Sciences >https://www.agci.org/redhen/contact/3091\">https://www.agci.org/sites/default/files/styles/headshot/public/default_images/AGCI_profile_sm.jpg?itok=7Trdel1u\">https://www.agci.org/redhen/contact/3091\">Curtis Deutsch>>>https://www.agci.org/redhen/contact/3092\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Ronald.jpg?itok=Qre04udp\">https://www.agci.org/redhen/contact/3092\">Pamela Ronald>>>https://www.agci.org/redhen/contact/3093\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Tewksbury.jpg?itok=gdBNWssA\">https://www.agci.org/redhen/contact/3093\">Josh Tewksbury>>"] }, { "post_title": "Impacts of Land Use and Land Management on Earth System Evolution, Biogeochemical Cycles, Extremes and Inter-Sectoral Dynamics", "authors": ["https://www.agci.org/redhen/contact/2511\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/CalvinK_0.jpg?itok=rIidxNOX\">https://www.agci.org/redhen/contact/2511\">Kate Calvin>Pacific Northwest National Laboratory>Earth Scientist>https://www.agci.org/redhen/contact/2052\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/13S2_Hurtt.jpg?itok=iQsU00Xe\">https://www.agci.org/redhen/contact/2052\">George Hurtt>University of Maryland>Professor>https://www.agci.org/redhen/contact/2055\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Lawrence_photo.png?itok=qCnfHCfg\">https://www.agci.org/redhen/contact/2055\">David Lawrence>National Center for Atmospheric Research (NCAR)>Senior Scientist "] }, { "post_title": "Advancing the Theory and Practice of Urban Heat Resilience", "authors": ["https://www.agci.org/redhen/contact/3175\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/ladd-keith-sm.jpg?itok=cnW3QjGu\">https://www.agci.org/redhen/contact/3175\">Ladd Keith>University of Arizona>Assistant Professor>https://www.agci.org/redhen/contact/3176\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Dave%20Hondula.jpg?itok=ewI2DCd_\">https://www.agci.org/redhen/contact/3176\">David Hondula>Arizona State University>Senior Sustainability Scientist; Associate Professor; Faculty Affiliate >https://www.agci.org/redhen/contact/3179\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Hunter-Professional-Cropped-291x300.jpg?itok=etdVjEL7\">https://www.agci.org/redhen/contact/3179\">Hunter Jones>National Oceanic and Atmospheric Administration>Climate and Health Projects Manager>https://www.agci.org/redhen/contact/2748\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/sara%20m.jpg?itok=048o8evr\">https://www.agci.org/redhen/contact/2748\">Sara Meerow>Arizona State University>Assistant Professor>https://www.agci.org/redhen/contact/3178\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/v-kelly-turner-600x800.jpg?itok=DikoBPnV\">https://www.agci.org/redhen/contact/3178\">V. Kelly Turner>University of California, Los Angeles>Assistant Professor"] }, { "post_title": "Advancing the Theory and Practice of Urban Heat Resilience", "authors": ["https://www.agci.org/redhen/contact/3175\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/ladd-keith-sm.jpg?itok=cnW3QjGu\">https://www.agci.org/redhen/contact/3175\">Ladd Keith>University of Arizona>Assistant Professor>https://www.agci.org/redhen/contact/3176\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Dave%20Hondula.jpg?itok=ewI2DCd_\">https://www.agci.org/redhen/contact/3176\">David Hondula>Arizona State University>Senior Sustainability Scientist; Associate Professor; Faculty Affiliate >https://www.agci.org/redhen/contact/3179\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Hunter-Professional-Cropped-291x300.jpg?itok=etdVjEL7\">https://www.agci.org/redhen/contact/3179\">Hunter Jones>National Oceanic and Atmospheric Administration>Climate and Health Projects Manager>https://www.agci.org/redhen/contact/2748\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/sara%20m.jpg?itok=048o8evr\">https://www.agci.org/redhen/contact/2748\">Sara Meerow>Arizona State University>Assistant Professor>https://www.agci.org/redhen/contact/3178\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/v-kelly-turner-600x800.jpg?itok=DikoBPnV\">https://www.agci.org/redhen/contact/3178\">V. Kelly Turner>University of California, Los Angeles>Assistant Professor"] }];
for (const post of arr) {
post.authors = post.authors[0].match(/(?<=">(?!https))[^>]+/g)
}
console.log(arr);
Use filter() to remove the URLs, then use join() to concatenate the remaining elements back into a string.
arr = [{
"post_title": "Food System Impacts of Pests & Pathogens in a Changing Climate",
"authors": [
"https://www.agci.org/redhen/contact/1520\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Roz_low_res_9_11_cropped.jpg?itok=vDp_RwzD\">https://www.agci.org/redhen/contact/1520\">Rosamond Lee Naylor>Stanford University>William Wrigley Professor of Earth System Science; Founding Director of the Center on Food Security and the Environment; Senior Fellow at the Stanford Woods Institute for the Environment and the Freeman Spogli Institute for International Studies.>https://www.agci.org/redhen/contact/2354\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Battisti.jpg?itok=82GpfOY3\">https://www.agci.org/redhen/contact/2354\">David S Battisti>University of Washington>Tamaki Chair of Atmospheric Sciences >https://www.agci.org/redhen/contact/3091\">https://www.agci.org/sites/default/files/styles/headshot/public/default_images/AGCI_profile_sm.jpg?itok=7Trdel1u\">https://www.agci.org/redhen/contact/3091\">Curtis Deutsch>>>https://www.agci.org/redhen/contact/3092\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Ronald.jpg?itok=Qre04udp\">https://www.agci.org/redhen/contact/3092\">Pamela Ronald>>>https://www.agci.org/redhen/contact/3093\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Tewksbury.jpg?itok=gdBNWssA\">https://www.agci.org/redhen/contact/3093\">Josh Tewksbury>>"
]
},
{
"post_title": "Impacts of Land Use and Land Management on Earth System Evolution, Biogeochemical Cycles, Extremes and Inter-Sectoral Dynamics",
"authors": [
"https://www.agci.org/redhen/contact/2511\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/CalvinK_0.jpg?itok=rIidxNOX\">https://www.agci.org/redhen/contact/2511\">Kate Calvin>Pacific Northwest National Laboratory>Earth Scientist>https://www.agci.org/redhen/contact/2052\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/13S2_Hurtt.jpg?itok=iQsU00Xe\">https://www.agci.org/redhen/contact/2052\">George Hurtt>University of Maryland>Professor>https://www.agci.org/redhen/contact/2055\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Lawrence_photo.png?itok=qCnfHCfg\">https://www.agci.org/redhen/contact/2055\">David Lawrence>National Center for Atmospheric Research (NCAR)>Senior Scientist "
]
},
{
"post_title": "Advancing the Theory and Practice of Urban Heat Resilience",
"authors": [
"https://www.agci.org/redhen/contact/3175\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/ladd-keith-sm.jpg?itok=cnW3QjGu\">https://www.agci.org/redhen/contact/3175\">Ladd Keith>University of Arizona>Assistant Professor>https://www.agci.org/redhen/contact/3176\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Dave%20Hondula.jpg?itok=ewI2DCd_\">https://www.agci.org/redhen/contact/3176\">David Hondula>Arizona State University>Senior Sustainability Scientist; Associate Professor; Faculty Affiliate >https://www.agci.org/redhen/contact/3179\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Hunter-Professional-Cropped-291x300.jpg?itok=etdVjEL7\">https://www.agci.org/redhen/contact/3179\">Hunter Jones>National Oceanic and Atmospheric Administration>Climate and Health Projects Manager>https://www.agci.org/redhen/contact/2748\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/sara%20m.jpg?itok=048o8evr\">https://www.agci.org/redhen/contact/2748\">Sara Meerow>Arizona State University>Assistant Professor>https://www.agci.org/redhen/contact/3178\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/v-kelly-turner-600x800.jpg?itok=DikoBPnV\">https://www.agci.org/redhen/contact/3178\">V. Kelly Turner>University of California, Los Angeles>Assistant Professor"
]
},
{
"post_title": "Advancing the Theory and Practice of Urban Heat Resilience",
"authors": [
"https://www.agci.org/redhen/contact/3175\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/ladd-keith-sm.jpg?itok=cnW3QjGu\">https://www.agci.org/redhen/contact/3175\">Ladd Keith>University of Arizona>Assistant Professor>https://www.agci.org/redhen/contact/3176\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Dave%20Hondula.jpg?itok=ewI2DCd_\">https://www.agci.org/redhen/contact/3176\">David Hondula>Arizona State University>Senior Sustainability Scientist; Associate Professor; Faculty Affiliate >https://www.agci.org/redhen/contact/3179\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/Hunter-Professional-Cropped-291x300.jpg?itok=etdVjEL7\">https://www.agci.org/redhen/contact/3179\">Hunter Jones>National Oceanic and Atmospheric Administration>Climate and Health Projects Manager>https://www.agci.org/redhen/contact/2748\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/sara%20m.jpg?itok=048o8evr\">https://www.agci.org/redhen/contact/2748\">Sara Meerow>Arizona State University>Assistant Professor>https://www.agci.org/redhen/contact/3178\">https://www.agci.org/sites/default/files/styles/headshot/public/img-contact/v-kelly-turner-600x800.jpg?itok=DikoBPnV\">https://www.agci.org/redhen/contact/3178\">V. Kelly Turner>University of California, Los Angeles>Assistant Professor"
]
}
];
arr.forEach(post => post.authors[0] = post.authors[0].split('>')
.filter(item => !item.includes('https://www.agci.org'))
.join(','));
console.log(arr);
I have products.json in which I have data. Now, I wish to render it using Reactjs.
products.json
[
{
"id": 1,
"productName": "Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops",
"price": 109.95,
"description": "Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday",
"category": "men's clothing",
"image": "https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg",
"specification": {}
},
{
"id": 2,
"productName": "Mens Casual Premium Slim Fit T-Shirts ",
"price": 22.3,
"description": "Slim-fitting style, contrast raglan long sleeve, three-button henley placket, light weight & soft fabric for breathable and comfortable wearing. And Solid stitched shirts with round neck made for durability and a great fit for casual fashion wear and diehard baseball fans. The Henley style round neckline includes a three-button placket.",
"category": "men's clothing",
"image": "https://fakestoreapi.com/img/71-3HjGNDUL._AC_SY879._SX._UX._SY._UY_.jpg",
"specification": {}
}
]
app.js
function App(){
return(
)
}
I want the json data to be rendered through app.js.
My Take On:
I'm new to Reactjs and JSON and was thinking of using fetch, response but I'm not sure how can I do it.
Can someone please help?
First you have to put your data in variable
For example:
const data = [
{
"id": 1,
"productName": "Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops",
"price": 109.95,
"description": "Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday",
"category": "men's clothing",
"image": "https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg",
"specification": {}
},
{
"id": 2,
"productName": "Mens Casual Premium Slim Fit T-Shirts ",
"price": 22.3,
"description": "Slim-fitting style, contrast raglan long sleeve, three-button henley placket, light weight & soft fabric for breathable and comfortable wearing. And Solid stitched shirts with round neck made for durability and a great fit for casual fashion
wear and diehard baseball fans. The Henley style round neckline includes a three-button
placket.",
"category": "men's clothing",
"image": "https://fakestoreapi.com/img/71-3HjGNDUL._AC_SY879._SX._UX._SY._UY_.jpg",
"specification": {}
}
]
The you have to map through your array
Like this
function App(){
return (
<div>
{data.map((d) => (
<div key={d.id}>
<p>ID: {d.id}</p>
<p>Product Name: {d.productName}</p>
<p>Price: {d.price}</p>
<p>Description: {d.description}</p>
<p>Category: {d.category}</p>
<p>
Image: <img src={d.image} width="100" />
</p>
<br />
<br />
</div>
))}
</div>
);
}
Then you can add CSS to make it look better!
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>
I have js files Dashboard and Adverts. I managed to get Dashboard to list the information in one json file (advertisers), but when clicking on an advertiser I want it to navigate to a separate page that will display some data (Say title and text) from the second json file (productadverts). I can't get it to work. Below is the code for the Dashboard and next for Adverts. Then the json files
import * as React from 'react';
import { Text, View, StyleSheet, Image, FlatList, TouchableOpacity } from 'react-native';
import advertisers from '../data/advertisers.json';
export default class Advertisers extends React.Component {
rendItem = listItem => {
let item = listItem.item
return (
<TouchableOpacity onPress={() => this.advertSelected(item)}>
<Text>
{' '}{item.id}{' '}{item.company}{' '}
</Text>
</TouchableOpacity>
);
};
advertSelected = (item)=>{
this.props.navigation.navigate("Adverts",{advert:item})
}
render() {
return (
<View style={styles.container}>
<Text style={styles.title}>List of advertisers</Text>
<FlatList
style={styles.list}
data={advertisers}
renderItem={this.rendItem}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: { marginTop: 30, marginLeft: 20 },
title: { fontSize: 20 },
list: { paddingTop: 20 },
});
Adverts
import * as React from 'react';
import { Text, View, StyleSheet, Image, FlatList, TouchableOpacity } from 'react-native';
import adverts from '../data/productadverts.json';
export default class Adverts extends React.Component {
rendItem = listItem => {
let item = listItem.item
let advert = this.props.navigation.getParam("advert")
let pic = advert.picture
let title = advert.title;
let id = advert.id;
};
render() {
return (
<View style={styles.container}>
<Text style={styles.title}>List of advertisers</Text>
<FlatList
style={styles.list}
data={adverts}
renderItem={this.rendItem}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: { marginTop: 30, marginLeft: 20 },
title: { fontSize: 20 },
list: { paddingTop: 20 },
});
advertisers.json
[
{
"company": "Fujifilm",
"id": 1,
"address": "St Martins Business Centre, St Martins Way, Bedford MK42 0LF",
"contactperson": "Carrie Perrett",
"contactnumber": "01234572000",
"emailaddress": "carrie#fuji.co.uk",
"logo": "https://logos-download.com/wp-content/uploads/2016/04/Fujifilm_logo_slogan_value_from_innovation.jpg"
},
{
"company": "Boeing",
"id": 2,
"address": "25 Victoria St, Westminster, London SW1H 0EX",
"contactperson": "Joanne Cumner",
"contactnumber": "02073401900",
"emailaddress": "jo#boeing.co.uk",
"logo": "https://www.govconwire.com/wp-content/uploads/2013/06/boeing-logo.jpg"
},
{
"company": "IBM",
"id": 3,
"address": "Birmingham Rd, Warwick CV34 5AH",
"contactperson": "Allan Elborn",
"contactnumber": "01926464000",
"emailaddress": "allan#ibm.co.uk",
"logo": "https://d15shllkswkct0.cloudfront.net/wp-content/blogs.dir/1/files/2012/08/ibm-logo.jpeg"
},
{
"company": "Fujitsu",
"id": 4,
"address": "55 Jays Cl, Basingstoke RG22 4BY",
"contactperson": "Alex Taylor",
"contactnumber": "08433545555",
"emailaddress": "alex#Fujitsu.co.uk",
"logo": "https://i.pinimg.com/originals/48/dc/fc/48dcfcd5df1834f66d029d7d34fae26d.png"
}
]
productadverts.json
[
{
"title": "ICT and Fujifilm’s new wave of innovation",
"id": 1,
"text": "Taking outstanding ICT achievements to the next level. ICT continues to advance rapidly. One recent example is the Internet of Things (IoT), in which devices and appliances have Internet connectivity and ICT functions built in. Moreover, ICT appears ready to take off in industry as never before, spurred by new advances in such technologies as artificial intelligence (AI) and virtual reality (VR). Some even view these trends in ICT as having the potential to lead to a new Industrial Revolution. As a leading technology company, Fujifilm is poised to become a major creative force in ICT and drive its own wave of innovation.",
"picture": "https://2df223ae-a-62cb3a1a-s-sites.googlegroups.com/site/eportfolioduaa/home/advantages-and-disadvantages-of-i-c-t/ict%202.png?attachauth=ANoY7cpUeQC5IlBqWx_cSW5wq5f4lDOPpWph4cfUpWUbE5h-fxfKatvv_ztmibYt834f8GHLpHcgZ6yA3wmc7c7veFhbf5NMke0MAkprLtZZHdllza0Q62BOEj3SHvZMg4rGKJegcIwfb6zW8a4OqAdgqFYvU1BCtNm25YqpngDRRN0HPqt8PmulWjVk2TS4jDWOt4KZfAd9pznmf8fi3Vw-zZJ0Ne_yFRON763E-2v8YzwRFc3yui_HfDE3HsqxcF3JIOizhQSVnqnJStlxeyzTDH_1yL8iZg%3D%3D&attredirects=0",
"advertiser": "Fujifilm"
},
{
"title": "Technologies",
"id": 2,
"text": "Fujifilm is a technology company. A photography company. Although quite a few people still have this image of Fujifilm, today it’s so much more. By leveraging the technologies it originally developed for the photography industry and continuously and proactively pursuing advanced R&D, Fujifilm has created businesses in multiple high-tech fields and become a technology-oriented company. ",
"picture": "https://logos-download.com/wp-content/uploads/2016/04/Fujifilm_logo_slogan_value_from_innovation.jpg",
"advertiser": "Fujifilm"
},
{
"title": "2020 Call for Code Global Challenge",
"id": 3,
"text": "Get inspired. Join the fight. Impact the world. Congratulations to the initial COVID-19 solutions that are now receiving deployment support. They show how technology can help small businesses find assistance after a crisis, redefine the queuing experience and guide us to the right medical advice. Developers and problem solvers, remember you have until July 31 to submit your open source solutions.",
"picture": "https://res.cloudinary.com/practicaldev/image/fetch/s--YBeZKs5E--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/c5zqnlp91mjy1v4uqaog.png",
"advertiser": "IBM"
},
{
"title": "It’s not about the data – it's what you do with it!",
"id": 4,
"text": "Power your operations and gain valuable insights using data analytics. Boeing AnalytX utilizes our aerospace expertise with data-based information to give you empowered decision support to optimize your operation and mission. Applications using Boeing predictive analytics give customers a glimpse into the near-future; more time to evaluate, plan and manage solutions. Boeing AnalytX offers three interrelated categories of analytics enabled products and services customers may easily mix and match to meet needs and goals. Digital Solutions – a set of analytics enabled software applications addressing the needs of crew and fleet scheduling, flight/mission planning and operations, maintenance planning and management, and inventory and logistics management. Analytics Consulting Services – a group of aviation, business, and analytics professionals who are ready to help customers improve their operational performance, efficiency, and economy. Self-Service Analytics – our newest category, that opens up the data behind the digital solutions for customers to explore and discover new insights and opportunities using Boeing provided analytics tools. ",
"picture": "https://www.govconwire.com/wp-content/uploads/2013/06/boeing-logo.jpg",
"advertiser": "Boeing"
},
{
"title": "Rethinking business and society in times of crisis",
"id": 5,
"text": "The continued spread and effects of the Coronavirus (COVID-19) are disrupting the everyday lives of people, society and businesses alike, and triggering inevitable and reasonable concerns among us all. Alongside our ongoing commitment to supporting many of the critical systems on which the UK relies every day, we have made it a priority to look at where Fujitsu technology and innovation can support the response to COVID-19. ",
"picture": "https://i.pinimg.com/originals/48/dc/fc/48dcfcd5df1834f66d029d7d34fae26d.png",
"advertiser": "Fujitsu"
}
]
The new object to get params in React Navigation 5 is:
this.props.route.params
Try to get the advert param using:
const { advert } = this.props.route.params;
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