Related
how can I access the previous element of this array of objects by the attribute "id", when the id is not sequenced one after the other. Assuming im in the las item of this array (id 6) and want to access to the previous one (id 4), but the code need to be automatic, like dont the only that element, I think it need to ask if the previous id is "null" to substract n number from the id to reach that element and to work in every part of the array. Thanks
[
{
"id": 1,
"nombre": "DITTO-X2 Looper",
"precio": "10999",
"img": "DITTO-X2.png",
"categoria": "pedales",
"sub_categoria": "loop_pedal",
"descripcion": "looper",
"marca": "ditto"
},
{
"id": 2,
"nombre": "Guitarra Taylor 562ce",
"precio": "73999",
"img": "guitarra562ce.png",
"categoria": "cuerdas",
"sub_categoria": "guitarra_acustica",
"marca": "taylor",
"descripcion": "Taylor’s Grand Concert 12-strings reaffirm Taylor’s heritage of easy-playing double course instruments thanks to a lap-friendly body size, a 12-fret neck, and a 24-7/8-inch scale length. The slinky handfeel makes fretting and bending strings easier, the neck and body are comfortably balanced, and the compact body produces a clear 12-string voice. The hardwood mahogany top adds just enough compression to the attack to smooth out the response, bringing an appealing consistency across the tonal spectrum, while still capturing the beautiful octave shimmer. V-Class bracing adds another dimension of musicality, improving volume and sustain so that notes and chords bloom and expand as they resonate. It makes a great 12-string choice for tracking in a studio, and behaves well with other instruments in a live setting. Refined aesthetic touches include a shaded edgeburst body and neck, faux tortoise shell binding, a rosette of faux tortoise shell and grained ivoroid, and a grained ivoroid Century fretboard inlay."
},
{
"id": 4,
"nombre": "BC-1x",
"precio": "38000",
"img": "1633645625329_img_.png",
"categoria": "pedales",
"sub_categoria": "bass_pedal",
"descripcion": "Pedal",
"marca": "boss"
},
{
"id": 6,
"nombre": "VE-500",
"precio": "30000",
"img": "1634188562527_img_.jpg",
"sub_categoria": "vocal_pedal",
"marca": "BOSS",
"descripcion": "If you’re like most guitarists, you spend a lot of time choosing the right amps and pedals to craft your own personalized sound. But if you sing in your band as well, it hasn’t always been so easy to give your vocal sounds that same attention to detail—until now. The advanced VE-500 Vocal Performer provides everything you need to achieve impressive vocal harmonies and effects on stage, and all in streamlined stompbox that integrates seamlessly with the regular guitar effects on your pedalboard."
}
]
Find index by Array.findIndex then get the result by Array[index-1].
const inputArray = [{
"id": 1,
"nombre": "DITTO-X2 Looper",
},
{
"id": 2,
"nombre": "Guitarra Taylor 562ce"
},
{
"id": 4,
"nombre": "BC-1x"
},
{
"id": 6,
"nombre": "VE-500"
}
]
const inputId = 6;
const indexById = inputArray.findIndex(e => e.id == inputId);
console.log(inputArray[indexById-1]);
Here is a step by step solution:
var currentId = 6;
Use findIndex to find the index of the object with currentId (https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex)
var currentIndex = arr.findIndex(function (item) {
return item.id === currentId;
});
If the index is 0 there are no previous item, if it's -1 there are no item with id: currentId
if (currentIndex === 0 || currentIndex === -1) {
// Invalid currentIndex
}
Get the array item with index currentIndex - 1
var previousElement = arr[currentIndex - 1];
So I tried getting Vue.js to arrange elements numerically by using "sortBy".
Obviously, I failed. I searched the web but got no satisfactory results, so anybody could help me?
HTML (not the whole thing, just the table that Vue.js renders)
<table class="ui celled table">
<thead>
<tr>
<th #click="sortBy='name'">Name</th>
<th #click="sortBy='cal'">Caliber</th>
<th #click="sortBy='r'">Range (max-min)(studs)</th>
<th #click="sortBy='dmg'">Damage</th>
<th #click="sortBy='cap'">Capacity</th>
<th #click="sortBy='rpm'">Rate of Fire</th>
<th #click="sortBy='multi'">Damage Multiplier (Head/Torso)</th>
<th #click="sortBy='desc'">Description</th>
<th #click="sortBy='rank'">Rank Unlock</th>
</tr>
</thead>
<tbody>
<tr v-for="list in lists">
<td>{{list.name}}</td>
<td>{{list.cal}}</td>
<td>{{list.r}}</td>
<td>{{list.dmg}}</td>
<td>{{list.cap}}</td>
<td>{{list.rpm}}</td>
<td>{{list.multi}}</td>
<td>{{list.desc}}</td>
<td>{{list.rank}}</td>
</tr>
</tbody>
<tfoot>
<tr>
<th colspan="100%">{{sortedlists.length}} guns</th>
</tr>
</tfoot>
</table>
JS
new Vue({
el: "#main",
data: {
lists: [
{
"name": "M9",
"cal": "9×19mm",
"dmg": "35-10",
"cap": "15+1 / 105",
"rpm": "780",
"multi":"1.50/1.10",
"desc": "A 9mm Italian pistol. One of the first 'wonder nines'. High capacity with deep reserves, light recoil, and high velocity. ",
"r": "40-80",
"rank": "0"
},
{
"name": "GLOCK 17 (G17)",
"cal": "9×19mm",
"dmg": "34-10",
"cap": "17+1/102",
"rpm": "780",
"r":"40-90",
"multi":"1.50/1.10",
"desc": "A 9mm Austrian pistol renowned for its simplicity and ruggedness. Compared to the M9, it has a higher capacity, but less muzzle velocity.",
"rank": "1"
},
{
"name": "M1911",
"cal": ".45 ACP",
"dmg": "48-29",
"cap": "8+1/56",
"rpm": "720",
"r":"55-90",
"multi":"1.40/1.15",
"desc": "A classic American pistol brought into the modern age. Very high damage up close, with poor velocity and small magazine size.",
"rank": "2"
},
{
"name": "DESERT EAGLE (DEAGLE) L5",
"cal": ".44 MAGNUM",
"dmg": "56-32",
"cap": "8+1/40",
"rpm": "400",
"r":"50-80",
"multi":"2.00/ 1.30",
"desc": "A modern version of the iconic Israeli-American pistol. This specific model has been lightened as well as upgraded with dual Picatinny rails and a much-needed muzzle brake. Very high damage with the capacity to instantly kill to the head up close, with rough recoil.",
"rank": "3"
},
{
"name": "M45A1",
"cal": ".45 ACP",
"dmg": "45-28",
"cap": "10+1/60",
"rpm": "670",
"r":"50-95",
"multi":"1.40/1.15",
"desc": "A modern American pistol with many custom parts. High damage, medium capacity, strong recoil.",
"rank": "4"
},
{
"name": "FIVE SEVEN",
"cal": "5.7×28mm",
"dmg": "29-22",
"cap": "20+1/100",
"rpm": "800",
"r":"80-120",
"multi":"1.40/1.20",
"desc": "A modern Belgian pistol firing a unique caliber. Poor close-in performance, with great ranged performance, high velocity, large magazine, wall penetration and deep reserves.",
"rank": "5"
},
{
"name": "ZIP 22",
"cal": ".22 LONG RIFLE",
"dmg": "15-12",
"cap": "10+1/180",
"rpm": "1000 SEMI",
"r":"30-60",
"multi":"2.80/1.00",
"desc": "A modern American 'pistol' with questionable quality. Abysmal damage, but with deep reserves and a high headshot multiplier. A weapon so bad it killed a million dollar company. 3 shots to the head at all ranges.",
"rank": "6"
},
.
.
.
.
etc all the way to "rank": "100"
{
"name": "MG42**",
"cal": "7.62 NATO",
"dmg": "36-20",
"cap": "50/250",
"rpm": "1200 AUTO",
"multi":"1.40/1.00",
"desc": "The original, the iconic, the feared... The buzzsaw of the axis powers during the second world war, back to prove it’s worth in the modern warzone. Fires extremely fast and hits even harder, but is slow and inaccurate.",
"rank": "100"
},
],
sortBy: "rank",
filterByName: "",
counter: 0
},
computed: {
sortedlists() {
return this.lists.filter(
list => list.name.includes(this.filterByName)
).sort(
(a, b) => a[this.sortBy].localeCompare(b[this.sortBy])
);
}
}
});
EDIT: I didn't include the whole javascript so I thought I might as well update the questions to make it clearer. So as I said, the `
computed:
{
sortedlists() {
return this.lists.filter(
list => list.name.includes(this.filterByName)
).sort(
(a, b) => a[this.sortBy].localeCompare(b[this.sortBy])
);
}`
doesn't arrange the elements in numerical order.
etc. all the way to "rank": "100".
Vue arranges the elements in a way like 0,1,10,100,11,2,20,21........29,3,30,31,32,33,.....39,4,40,....48,49 etc
You get the idea. It just doesn't seem to arrange the elements like 1,2,3,4,5,6,7,8,9,10,11,12 etc. which I want it to do.
Any helpful answers?
You need to sort by rank as a number and not as a string. Alphabetical order is exact that you got: 1,10,100,11,2,20,21.
const sortedList = lists.splice().sort((x1, x2) => (parseInt(x1.rank) - parseInt(x2.rank)))
Ahhhh seems like I found the answer after some serious tinkering with the code.
I changed it to the following:
computed: {
sortedlists() {
return this.lists.filter(
list => list.name.includes(this.filterByName)
).sort(
(a, b) => a[this.sortBy] - b[this.sortBy]
);
}
}
I started learning node.js and I am facing an error.
Here's the code:
const server = http.createServer((req, res) =>{ //request, response
const pathName = req.url;
if (pathName === '/' || pathName === '/overview'){
res.end('This is the OVERVIEW') // res trimite catre client, req trimite catre server
} else if (pathName === '/product'){
res.end('This is the PRODUCT');
} else if (pathName === '/api') {
fs.readFile(`${__dirname}/dev-data/data.json`, 'utf-8', (err, data) => {
const productData = JSON.parse(data);
response.writeHead(200, { 'Content-type': 'application/json' });
response.end(data);
});
} else{
res.writeHead(404, {
'Content-type': 'text/html',
'my-own-header': 'hello-world'
});
res.end('<h1>This page could not be found!</h1>');
}
res.end('Hello from the server!');
});
the problem is in this if:
else if (pathName === '/api') {
fs.readFile(`${__dirname}/dev-data/data.json`, 'utf-8', (err, data) => {
const productData = JSON.parse(data);
response.writeHead(200, { 'Content-type': 'application/json' });
response.end(data);
});
The error i get:
undefined:1
undefined
^
SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse ()
at ReadFileContext.callback (c:\Users\40721\Desktop\nodeJs&Express\complete-node-bootcamp-master\1-node-farm\index.js:49:38)
at FSReqCallback.readFileAfterOpen [as oncomplete] (fs.js:257:13)
The data.json file i want to read from is this:
[
{
"id": 0,
"productName": "Fresh Avocados",
"image": "🥑",
"from": "Spain",
"nutrients": "Vitamin B, Vitamin K",
"quantity": "4 🥑",
"price": "6.50",
"organic": true,
"description": "A ripe avocado yields to gentle pressure when held in the palm of the hand and squeezed. The fruit is not sweet, but distinctly and subtly flavored, with smooth texture. The avocado is popular in vegetarian cuisine as a substitute for meats in sandwiches and salads because of its high fat content. Generally, avocado is served raw, though some cultivars, including the common 'Hass', can be cooked for a short time without becoming bitter. It is used as the base for the Mexican dip known as guacamole, as well as a spread on corn tortillas or toast, served with spices."
},
{
"id": 1,
"productName": "Goat and Sheep Cheese",
"image": "🧀",
"from": "Portugal",
"nutrients": "Vitamin A, Calcium",
"quantity": "250g",
"price": "5.00",
"organic": false,
"description": "Creamy and distinct in flavor, goat cheese is a dairy product enjoyed around the world. Goat cheese comes in a wide variety of flavors and textures, from soft and spreadable fresh cheese to salty, crumbly aged cheese. Although it’s made using the same coagulation and separation process as cheese made from cow’s milk, goat cheese differs in nutrient content."
},
{
"id": 2,
"productName": "Apollo Broccoli",
"image": "🥦",
"from": "Portugal",
"nutrients": "Vitamin C, Vitamin K",
"quantity": "3 🥦",
"price": "5.50",
"organic": true,
"description": "Broccoli is known to be a hearty and tasty vegetable which is rich in dozens of nutrients. It is said to pack the most nutritional punch of any vegetable. When we think about green vegetables to include in our diet, broccoli is one of the foremost veggies to come to our mind. Broccoli is a cruciferous vegetable and part of the cabbage family, which includes vegetables such as Brussel sprouts and kale. Although the tastes are different, broccoli and these other vegetables are from the same family."
},
{
"id": 3,
"productName": "Baby Carrots",
"image": "🥕",
"from": "France",
"nutrients": "Vitamin A, Vitamin K",
"quantity": "20 🥕",
"price": "3.00",
"organic": true,
"description": "The carrot is a root vegetable that is often claimed to be the perfect health food. It is crunchy, tasty and highly nutritious. Carrots are a particularly good source of beta-carotene, fiber, vitamin K, potassium and antioxidants. Carrots have a number of health benefits. They are a weight loss friendly food and have been linked to lower cholesterol levels and improved eye health."
},
{
"id": 4,
"productName": "Sweet Corncobs",
"image": "🌽",
"from": "Germany",
"nutrients": "Vitamin C, Magnesium",
"quantity": "2 🌽",
"price": "2.00",
"organic": false,
"description": "Also known as maize, corn is one of the most popular cereal grains in the world. Popcorn and sweet corn are commonly eaten varieties, but refined corn products are also widely consumed, frequently as ingredients in foods. These include tortillas, tortilla chips, polenta, cornmeal, corn flour, corn syrup, and corn oil. Whole-grain corn is as healthy as any cereal grain, rich in fiber and many vitamins, minerals, and antioxidants."
}
]
Are you storing the image property as a location to the image? JSON only accepts these datatypes:
a string
a number
an object (JSON object)
an array
a boolean
null
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 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>
);