Loop over Json object -- React - reactjs

I have a API for which I would like to loop over to get all the value of its keys. But unfortunately Iam only getting the keys for it.
My code until now:
...
const image_link = JSON.stringify(image);
const parsed_link = JSON.parse(image_link);
console.log('1st link', parsed_link[0].Header) // gives "abc.jpg"
...
...
<div>
{
Object.keys(parsed_link).map((e, i) => {
console.log(parsed_link);
console.log(e); // gives integers like 0,1,2 etc...
console.log(i); // gives integers like 0,1,2 etc...
<img src={e} alt="something" width="300" height="200" />;
return null;
})
}
</div>
...
...
API looks like this:
"Header": [
{
"image": "abc.jpg"
},
{
"image": "xyz.jpg"
},
{
"image": "lmn.jpg"
}
]
Please suggest, where am I goin wrong.
Thanks in advance

If you want to loop through an array, you can use map function.
If you want to loop through an object, you can have to convert the object into an array using Object.keys(YOUR_OBJECT) (if you want to get the key) or Object.values(YOUR_OBJECT) (if you want to get the values) than use map function.
You can directly print the array of data into an array of views. You have to return a view like these:
YOUR_ARRAY.map((item, index) => (
<div>YOUR VIEW</div>
))
// or
YOUR_ARRAY.map((item, index) => {
return(
<div>YOUR VIEW</div>
)
})
Note: you can only return a single parent view inside the return value. If you want to return multiple views inside the return value, you have to wrap them inside a single <div></div> or <React.Fragment></React.Fragment> or <></> parent.
In your code, I saw you wrote parsed_link[0].Header. So I assume that the API returns something like this:
[
{
"Header": [
{
"image": "abc.jpg"
},
{
"image": "xyz.jpg"
},
{
"image": "lmn.jpg"
}
],
...
},
...
]
Here is my answer:
<div>
{
parsed_link[0]['Header'].map((item, index) => (
<img
key={index}
src={item}
alt='something'
width='300'
height='200'
/>
)
}
</div>

Related

mapping through object which is inside object in react

I have roomFeature.js file inside which there is object named as roomFeature. Inside roomFeature there is another object named beds with childs "single: "1", double: "2",".
Here's what i am talking about:
const roomFeatures = {
roomFeature: {
bed: true,
sleep: {
single: "1",
double: "3",
},
}
}
how can i access "1" if the "sleep" is available?
I have tried:
{roomFeatures.roomFeature.sleep.map((data) => {
return (
<div>
<span>
<BsFillPersonFill />
</span>{" "}
sleeps {data.single}
</div>
);
})}
If you only want to access to "1" one time then you can directly use {roomFeatures.roomFeature.sleep.single}
If you are trying to loop through the sleep object, you should convert it to an array before you use map function.
let temp_sleep = Object(roomFeatures.roomFeature.sleep);
temp_sleep.keys().map(key => {
return (
<div>
<span>
<BsFillPersonFill />
</span>{" "}
sleeps {temp_sleep[key]}
</div>
);
})
The keys function will return an array of keys in the object, so you can use the map function on the array.

React | How to render only 1 object from an array that is part of a nested object

I have this data structure:
const data = [
{
title: 'title',
description: 'description'
images: [
{ mainImg: 'url' },
{ img1: 'url' },
{ img2: 'url' },
{ img3: 'url' },
],
},
...
]
My question is, how can I render only the mainImg separated from the others? And how can I render the other images without the mainImg.
What I've tied so far is to map through the images like this: (I did mapped through data before)
{data.images.map((img, index) => (
<img
key={`image${index}`}
src={img.mainImg}
className={styles.mainImg}
/>
))
}
This worked, but the issue is that I map through all the images and when I open the consoles, all the images are rendered but they are not visible because they don't have the src tag. (I think).
Simply trying to use data.images.mainImg as the src value doesn't render anything, and also does not throw any errors.
Also, I have an issue trying to render all the other images except the mainImg. This is what I've tried but I get lost and I don't know what the src value should be.
{data.images
.filter((img) => img.mainImg != project.images.mainImg)
.map((img, index) => (
<img src={img} />
))
}
You could use hasOwnProperty : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
data.images.map((e, i) => {
if (e.hasOwnProperty('mainImg')) {
// Do something with mainImg
}
//Do something with the others
})
A JSfiddle with example : https://jsfiddle.net/RyanZee/hu189jxd/12/
Do you always have a mainImg at index 0? If so you can use
const [firstImg, ...imgs] = data.images;
return (
<>
<img src={firstImg.mainImg} ... />
{ imgs.map((img, index) => <img src={img[`img${index + 1}`]} /> }
</>
)

map function not working properly in object React

I have an array that contains as follows. I have successfully mapped the data and put it into the elements. but there are some values I couldn't get correctly. I have added a console.log to figure out the data. data is correct in the array, I want to get the Seats ("A1,B1") in here <h5><small>{seatNos.seats}</small></h5> but nothing is displaying. appreciate any help.
Data array
"data": {
"userBookings": [
{
"transactionId": 6357604,
"totalAmount": 350,
"createdAt": "2021-08-05 02:16:48",
"movieName": "Mortal Kombat",
"theaterName": "XxX Cinema",
"showTime": "17:30",
"refcode": "0016048GIN210805I",
"bookedSeats": [
{
"seatType": "Comfert",
"seats": "A1,B1",
"childTickets": 1,
"totalTickets": 2,
"bookedDate": "2021-08-05"
}
]
}
]
},
code
<div className="col-xl-5 col-lg-5 col-md-7 col-sm-7 col-xs-9 col-6" style={{paddingLeft:25}}>
<h5><b>{bookingsData.movieName}</b></h5>
<h5>{bookingsData.theaterName}</h5>
<h5><small>{bookingsData.showTime}</small></h5>
{bookingsData.bookedSeats.map((seatNos) => {
console.log(seatNos.seats);
<h5><small>{seatNos.seats}</small></h5>
})}
{/* <h5><small>{bookingsData.bookedSeats.seats}</small></h5> */}
</div>
You need to return element in map, and set key for this element:
{bookingsData.bookedSeats.map((seatNos, index) => {
console.log(seatNos.seats);
return <h5 key={index}><small>{seatNos.seats}</small></h5>
})}
Your arrow function inside the .map() doesn't return a value. You need a return before the JSX:
{bookingsData.bookedSeats.map((seatNos) => {
console.log(seatNos.seats);
return <h5><small>{seatNos.seats}</small></h5>
})}
Or to use the implicit return arrow function syntax (Either round brackets, or no brackets: () => () or () => returnedValue)
{bookingsData.bookedSeats.map((seatNos) => <h5>
<small>{seatNos.seats}</small>
</h5>)}
This is because you forgot the return
array.map((item) => {
return (
<p>{item.value}</p>
)
})

can not map array inside of object

I am lost here, can not find a way how to map through an array that is inside of object. I have received an object from API that includes an array wit values like this:
{
"shelters": [
{
"id": 1,
"name": "Útulok pre psov - TEZAS"
},
{
"id": 2,
"name": "OZ Tuláčik Brezno"
}
]
}
now I need to iterate through the array that is inside and take action on every item to populate the DOM.
my code is:
render() {
// const { isPending, shelters} = this.props;
if (this.props.isPending === false) {
var listOfShelters = this.props.shelters;
console.log('loaded', typeof(listOfShelters), listOfShelters)
return (
<div>
<select style={this.selector} name="útulky" onChange={this.sendId}>
{ listOfShelters.shelters.map(function(shelter, i) {
<option id={shelter.id}>{shelter.name}</option>
})}
</select>
</div>
)
} else if (this.props.isPending === true) {
console.log('fetching')
return (
<select style={this.selector} name="útulky" onChange={this.sendId}>
<option id='0'> Nahravam Data... </option>
</select>
)}
}
I get typeof always an object even if I do this.props.shelters.shelters which should be direct access to that array. if I do this.props.shelters.shelters.map nothing happens, my list of shelters does not get populated. it stays empty. Where do I make the mistake here?
I have found what the problem was. I had different set of parentheses in the .map function, I was using {} instead of (). Now it works like a dream.

how to dynamically parse Json data using reactjs

I have a requirement to determine a generic standard approach to read the JSON data ( should be able to read any JSON structure) and display in reactjs page.
I know that if we know JSON structure, we can traverse through it and display the data in the page accordingly. But here JSON structure
should be dynamically determined via code and we should not code specifically for each JSON structure.
For example, I have given Sample1.json and Sample2.json files below. My program should be able to parse Sample1.json if I use it and display
them on the page. If I use Sample2.json, still it should be able to parse them and display the data dynamically. We should not have
code specifically like archive_header.tracking_id or stock_ledger_sales_key.version_number...etc.
Can someone please let me know how to handle this scenario?
Sample1.json
{
"archive_header": {
"tracking_id": "914553536-FRM01-20163609140455-000000001",
"archived_timestamp": "2018-05-08T09:14:04.055-05:00"
},
"journal_record_key": {
"location_number": "389234",
"dept_number": "28822"
},
"journal_record_detail": {
"financial_from_item_number": "771",
"financial_to_item_number": "771"
}
}
Sample2.json
{
"stock_ledger_sales_key": {
"version_number": "12",
"account_month_number": "01",
"account_year_number": "2016"
},
"stock_ledger_sales_detail": {
"mature_increase_mtd_percentage": "1.2",
"mature_increase_stdt_percentage": "2.3",
"mature_increase_ytd_percentage": "2"
}
}
You can just iterate over the keys recursively:
function recursively_iterate(object, parent_name="") {
output = ""
for (key in Object.keys(object)) {
if (typeof object[key] == "object") {
output = output + recursively_iterate(object[key], key)
}
output = output + parent_name + "." + key + ": " + object[key] + "\n"
}
return output
}
To display the information as you said, we can do something like this:
const jsonDOM = json => {
return Object.keys(json).map(key => {
return Object.keys(json[key]).map(child => {
return (<div>
<p>{child}</p>
<p>{json[key][child]}</p>
</div>
);
});
});
};
return (<div>
<h2>JSON 1</h2>
{jsonDOM(json1)}
<h2>JSON 2</h2>
{jsonDOM(json2)}
</div>
);
Here is the live demo
Hope it helps :)
You can use JSON.stringify and <pre> tag to output any json you like.
const sample1 = {
archive_header: {
tracking_id: "914553536-FRM01-20163609140455-000000001",
archived_timestamp: "2018-05-08T09:14:04.055-05:00"
},
journal_record_key: {
location_number: "389234",
dept_number: "28822"
},
journal_record_detail: {
financial_from_item_number: "771",
financial_to_item_number: "771"
}
};
const sample2 = {
stock_ledger_sales_key: {
version_number: "12",
account_month_number: "01",
account_year_number: "2016"
},
stock_ledger_sales_detail: {
mature_increase_mtd_percentage: "1.2",
mature_increase_stdt_percentage: "2.3",
mature_increase_ytd_percentage: "2"
}
};
class App extends React.Component {
render() {
return (
<div>
<h3>sample1</h3>
<pre>
<code>{JSON.stringify(sample1, null, 2)}</code>
</pre>
<h3>sample2</h3>
<pre>
<code>{JSON.stringify(sample2, null, 2)}</code>
</pre>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Resources