Deep level JSON Object referencing - arrays

I have searched and reviewed similar posts on this subject but no luck. I have valid JSON data returned to my app from my firebase Database but unable to reference the elements beyond first level. I need to pull the elements (url link) of the photos array object that is also an object of gallery array object. When i use the code snippet below I get the red screen listing all of the JSON object in the gallery object.
<TouchableOpacity >
<Image
source={{ uri: gallery }}
style={styles.roundedNavImageStyle}
/>
</TouchableOpacity>
When I change the source to reference what I need given the screenshot, I get errors "Cannot read property of [0] of undefined or Cannot read property photos of undefined.
<TouchableOpacity >
<Image
source={{ uri: gallery[0].photos }}
style={styles.roundedNavImageStyle}
/>
</TouchableOpacity>
Please help me. The photo links are the only elements of my JSON data I am unable to access which I need badly. I am able to access the image elements and other textual elements. I have also tried to simplify my JSON by removing the gallery node and starting with a photos node but getting the same issues. Thanks for your anticipated help. Please use my case rather than a generic json object to help me quicker.
Here's a snipet of my JSON object as stored in Firebase backend.
"places": [{
"id": "a",
"image": "https://res.cloudinary.com/obisi7/image/upload/v1537575323/tourNaija/slave/slavePic.jpg",
"title": "Slave Trade Museum",
"description": "Excerpts from Freeman Institute",
"subTitle": "One of many rare gems of history and education",
"phone": "",
"credit": "The Freeman Institute",
"gallery": [{
"id": "v1",
"photos": [{
"id": "p1",
"pic1": "https://res.cloudinary.com/obisi7/image/upload/v1537575322/tourNaija/slave/abolitionCannon.jpg",
"pic2": "https://res.cloudinary.com/obisi7/image/upload/v1537575322/tourNaija/slave/holdingCell.jpg",
"pic3": "https://res.cloudinary.com/obisi7/image/upload/v1537575322/tourNaija/slave/slaveMarket.jpg",
"pic4": "https://res.cloudinary.com/obisi7/image/upload/v1537575323/tourNaija/slave/slaveNoReturn.jpg",
"pic5": "https://res.cloudinary.com/obisi7/image/upload/v1537575323/tourNaija/slave/bibleAtBadagry.jpg",
"pic6": "https://res.cloudinary.com/obisi7/image/upload/v1537575322/tourNaija/slave/bridge.jpg"
}]
}]
},

Related

How to handle dynamic require images react native

i saved images to MongoDb with multer to path /uploads in my local static folder.
the object that i get from the data base when i get images look like :
Array [
Object {
"_id": "5fc4581a1b858e93a65136e7",
"desc": "19",
"image": "uploads/a2.jpg",
},
Object {
"_id": "5fc4584a873e544138a10a33",
"desc": "19",
"image": "uploads/a2.jpg",
},
]
now i want to show the array with desc and image so i defined a flat list and try to do:
<FlatList
numColumns={numColumns}
data={s}
renderItem={({ item, index }) => (
console.log("http://localhost:8080/" + item.image),
(
<View style={styles.imagecontainer}>
<Text>{item.desc}</Text>
{Object.keys(s).length === 0 ? null : (
<Image style={styles.image} source=
{require(`../../server/${item.image}`)} />/////////here is the problem
)}
</View>
)
)}
keyExtractor={(item, index) => index.toString()}
/>
now I understand that require should get only static string and not variables,
the question is how can I handle this to show the images and desc dynamically based on the array?
I read a lot of it on the internet but Dont find the answer for this...
I need somehow to convert the objects that I get and replace the image prop that gave me "uploads/a2.jpg" to {require(../../server/**here to put the image for each object**) but I Dont find a way to do that.
I faced the same issue, the only way I found it was to save images' IDs returned by the require() function.
console.log(require("image path"));
// return a number for example 5

How to access a local image using a local image url in a json file in react native?

I have problem in accessing the local image url in a json file. The images are stored in image directory. I have got some image addresses stored in a JSON array like this :
jsonResponse=
[ {"id": "1", "myImage": "./image/img1.png", "myText": "Anytext"},
…
]
const first = jsonResponse[0]
But when I try calling that using first.myImage in Image, it doesn't work; I'm able to get everything else. So, I try calling it like:
source={require('{first.myImage}')} as well as source={require({first.myImage})}
But it says, invalid prop type. I am able to access all other elements. I have also updated the JSON as:
[ {"id": "1", "myImage": "require('./image/img1.png')", "myText": "Anytext"},
…
]
source={first.myImage} OR source={{first.myImage}}
but that gives the same error too. Please help me.
makesure you are accessing the image in the same directory where image resides or else navigate to the image with proper path
I'm assuming you are able to retrieve the filepath from the json file and that the path is correct. Based on that, try using:
jsonResponse = [{"id": "1", "myImage": "./image/img1.png", "myText": "Anytext"}, ...]
Then on your app create two const to hold your variables. The first one you'll use to save the path you retrieve from the json. The second will be the one you'll use as source of your Image component.
constructor() {
const imagePath = first.myImage;
const image = require(imagePath);
}
...
<Image
source={image}
style={{ height: 30, width: 30, resizeMode: 'contain' }}
/>
...
Alternatively, you can also try importing the image this way:
import image from first.myImage;
JSON File:
{
"id": 2,
"name": "Toyota Corolla XLI\\Hatchback Automatic",
"details": "4 seater, diesel",
"picture": "./static/images/XLI.jpg",
"overcharge": "PKR 179 per excess km",
"weekday": "PKR 190/hr",
"weekend": "PKR 287/hr"
},
And then add inyour .js file like this:
{PostData.map((postDetail, index) => {
return (
<Link href="details">
<Card className="carditem">
<Card.Body style={{ cursor: "pointer" }}>
<Row>
<Col xs="12" sm="4">
<img
src={postDetail.picture}
class="d-block"
height="170"
/>

How to iterate through a JSON array and display specific information based on an API response value in React?

I'm building a ReactJS web application, I have a JSON array:
[{
"2149166938": {
"name": "Classical-42",
"icon": "/common/destiny2_content/icons/e6885dab15cafeaf0dbf80f1ff9b5eb8.jpg"
},
"2149166939": {
"name": "Countess SA/2",
"icon": "/common/destiny2_content/icons/de8906743db9fce201b33802c8498943.jpg"
},
"2154059444": {
"name": "The Long Goodbye",
"icon": "/common/destiny2_content/icons/fe07633a2ee87f0c00d5b0c0f3838a7d.jpg"
}
}]
When I make a call to an API I am returned a value of lets say 2154059444 which is the same value as the last object in my JSON file.
How would I iterate through the JSON file to find the object which has a value of 2154059444 and then access and render it's child values like name or icon?
you can do something like this. Your array is not proper please edit.
Create filtered data :
//here i am addding single dummy point you can make your function
l
et filteredData = [].concat(data.map(test => {
if(Object.keys(test)[0]==="2154059444"){
return test["2154059444"]
}
})).filter(Boolean)
and simply render it app like this .
{ filteredData.map(test => <div>{test.name}</div>)}
Here is live link
This is simple. JSON is equivalent to Javascript object. So you can do something like result[0]["2154059444"]. You might want to use JSON.parse for converting the JSON string to Javascript object.

Why *ngFor in Angular shows the new object first from the array of objects which is having .subscribe() method on in Ionic 3

I am new to Ionic 3 & Angular and ran into an issue with *ngFor and .subscribe() method. Please forgive me if it is an easy question. I tried to figure out the behaviour of http.get(..).map(..).subscribe() function when used along with *ngFor to maintain an array of objects and show the records to user using *ngFor on the .html template file but unable to know *ngFor's odd behaviour.
In my Ionic 3 App, I am getting the data using an API and storing it inside a component variable called "users" which is declared as below in component .ts file -
users: Array<any>;
I have below component function which gives me data for this users array -
addUser(count: number) {
this.http.get('https://randomuser.me/api/?results=' + count)
.map(data => data.json().results)
.subscribe(result => {
for (let val of result) {
this.users.push(val);
}
})
}
Initially, I get data for 10 users from the API using above component function by simply calling it inside my ngAfterViewInit() function like -
this.addUser(10);
This gives me 10 user record objects inside my users array which I show to the user using something like below in the view .html file -
<ion-card *ngFor="let user of users">
{{user.email}}
</ion-card>
At this time *ngFor puts the last array element at first in the view and shows the records in the descending order as the elements in the array starting from index 9 to 0.(LIFO order)
Now I start popping the last element from this users array using users.pop(); and push another element at the beginning at index 0 by shifting current elements using users.unshift(..) in below function and calling it as addNewUser(1); -
addNewUser(count: number) {
this.http.get('https://randomuser.me/api/?results=' + count)
.map(data => data.json().results)
.subscribe(result => {
for (let val of result) {
this.users.unshift(val);
}
})
}
At this moment, if we consider the first array which had 10 elements, the last object at index 9 had been removed and another element at index 0 has been added making the previous elements on index 0-8 to shift to index 1-9.
On doing so, my view gets updated which has *ngFor and surprisingly this time it shows the first element at first place which is actually on index 0 which is the one I recently put. This is opposite to the order earlier followed by *ngFor to render elements on the screen.
Why *ngFor in Ionic 3 view shows the recently inserted object element first from the array of objects which is dependent on the subscribe method .subscribe() method. I am really confused about this.
I really need to clear the concept of *ngFor and subscribe(). Please help me.
Note : The API mentioned above is publicly accessible for testing and you may call it to check the response structure if required.
Pasting a sample API response below on calling https://randomuser.me/api/?results=1 -
{
"results": [
{
"gender": "male",
"name": {
"title": "mr",
"first": "daniel",
"last": "stoll"
},
"location": {
"street": "9719 tannenweg",
"city": "cottbus/chosebuz",
"state": "bremen",
"postcode": 81443
},
"email": "daniel.stoll#example.com",
"login": {
"username": "greenleopard994",
"password": "chat",
"salt": "OUjisBdQ",
"md5": "8148d51998f3fef835a5f3979218c181",
"sha1": "131ae09d045b345efe36a330bf17a450b76f7de3",
"sha256": "94c3a362b5f516d0fb1d4e9dbb632d32d57b8886d5cc7bf0d5cedc99e7d55219"
},
"dob": "1957-04-26 22:07:14",
"registered": "2002-04-29 10:57:34",
"phone": "0556-4348870",
"cell": "0172-5116200",
"id": {
"name": "",
"value": null
},
"picture": {
"large": "https://randomuser.me/api/portraits/men/14.jpg",
"medium": "https://randomuser.me/api/portraits/med/men/14.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/men/14.jpg"
},
"nat": "DE"
}
],
"info": {
"seed": "8fd4afe85884c767",
"results": 1,
"page": 1,
"version": "1.1"
}
}
Refer this example showing my issue.
If you have a sorting issue with indexing and you think it's related.. you could work around the issue by assigning an index:
*ngFor="let user of users; let i = index"
and then reference the direct index value
users[i]
You should make a copy of that array. Editing array elements while looping them can lead to unexpected behaviour.

iterate over json object of arrays from ionic 2 post request

I guess I'm stuck on stupid. I've been at this for the last few hours and can't seen to figure it out. Admittedly, I am new to ng/ionic2.
I am trying to loop through the response from my post request. I am getting a valid(validated online) big, fat JSON object from my own web api. It looks like this:
`"details": [{
"item_ID": "4",
"item_attribute_ID": "JiggyJamband_1_642",
"item_color_bool": "false",
"item_name": "Test Item 4",
"item_price": "18.95",
"item_desc": "4 This is a test of the ajax input",
"item_gender": "Girls"
},
{ ... },
"attributes": {
"JiggyJamband_1_642": [{
"color": "no-color",
"Xs": "80",
"Sm": "0",
"Med": "0",
"Lrg": "0",
"Xl": "0",
"Xxl": "10"
}],
"JiggyJamband_5_5664": [{
"color": "no-color",
"Xs": "0",
"Sm": "0",
"Med": "0",
"Lrg": "0",
"Xl": "0",
"Xxl": "50"
}],
{ ... }`
I am able to access individual "details" and "attributes" like this:
this.itemsDataService.getRemoteData(urlCode)
.subscribe(response => {
this.itemsJson = response;
this.dObj = this.boothItemsJson.details;
//this.aObj = this.boothItemsJson.attributes;
this.aObj = response["attributes"]["JiggyJamband_1_642"];
});
My provider looks like this:
getRemoteData(urlCode): any {
return this.http.post('http://localhost/process-fe-app/_itemJson.php', JSON.stringify(urlCode))
.map(res => res.json()); }
My question: items in details is dynamic and has an item-attribute_ID that is related to at least 1 entry in attributes. Entrys for attributes are dynamic as well - each item can have multiple attributes. The array keys of the individual attributes are the static (sizes and colors) and either have values or they don't. I need to be able to loop over the attributes object (aObj) of arrays and the arrays inside them. I do not need the ngFor or ngIf statements as this data won't be directly displayed per se. The json data is returned just fine but I just need to be able to access it call methods on the based on the data (like putting into storage with the attribute ID as the key "JiggyJamband: color: no-color, xs:50, s:100... etc"
What I've tried: this tutorial https://www.youtube.com/watch?v=0kHJgw6Li_4, and googling ever iteration of the wording for this problem I could think of.
Perhaps this sample iteration will help you get your head around it.
this.itemsDataService.getRemoteData(urlCode)
.subscribe(response => {
for(var k in response){
for(var k2 in response[k]){
console.log([k,k2,response[k][k2]]);
}
}
});

Resources