How to map an array of objects in React Native - reactjs

How to map an array of objects in React Native
Api response data
Object {
"data": Object {
"1": Object {
"fk_i_attribute_id": "1",
"fk_i_item_id": "60730",
"locales": Object {
"en_US": "Car Make",
},
"pk_i_id": "12368",
"s_name": "Car Make",
"values": Object {
"355": Object {
"hierarchy": Object {
"355": Object {
"locales": Object {
"en_US": "Others Brands",
},
"pk_i_id": "355",
"s_name": "Others Brands",
},
},
"locales": Object {
"en_US": "Others Brands",
},
"pk_i_id": "355",
"s_name": "Others Brands",
},
},
},
"2": Object {
"fk_i_attribute_id": "2",
"values": Array [
Object {
"hierarchy": Array [],
"locales": Array [],
"pk_i_id": 0,
"s_name": "",
"s_value": "0",
},
],
},
Now I am trying to map through this data to display it on my screen:
{
data?.map(function (item, index) {
return (
{item.s_name}
);
})
}
But getting nothing

data should be an array , which in your case is an object.
Keep in mind map function only works with array and not with objects.
function App (){
// assume data is an array which you are getting from some api
return <View>
{ data?.map(function (item, index) { return (
<Text key={index} >
{item.s_name}
</Text>
)})
}
</View>
}

[
{
name: 'Sam',
email: 'somewhere#gmail.com'
},
{
name: 'Ash',
email: 'something#gmail.com'
}
].map((anObjectMapped, index) => {
return (
<p key={`${anObjectMapped.name}_{anObjectMapped.email}`}>
{anObjectMapped.name} - {anObjectMapped.email}
</p>
);
})

Related

React: How to render a list of items grouped by category (using .map)

I have an array (myArray), stored like so (in firebase):
[
{
"id": "1",
"Category": "Hardware",
"Name": "Xtreme"
},
{
"id": "123",
"Category": "Software",
"Name": "Obsolete"
},
{
"id": "12345",
"Category": "Software",
"Name": "V1"
},
{
"id": "1234567",
"Category": "Hardware",
"Name": "CPU"
}
]
I am using the following code:
const sorterAR = [];
myArray.forEach((item) => {
let cat = sorterAR.find(
(cat) => cat.id === item.id
);
if (!cat) {
cat = {
id: item.id,
Category: item.Category,
items: [],
};
sorterAR.push(cat);
}
cat.items.push(item);
});
And then displaying like so:
<div className="App">
{sorterAR.map((cat) => (
<>
<div>
<b>{cat.Category}</b>
</div>
<ul>
{cat.items.map((item) => (
<li>{item.Name}</li>
))}
</ul>
</>
))}
</div>
This works in that it produces an output like:
**Hardware**
Xtreme
**Hardware**
CPU
**Software**
Obsolete
**Software**
V1
How do I alter this to produce the following output:
**Hardware**
Xtreme
CPU
**Software**
Obsolete
V1
So that it displays the category name and then all the items in that category, and then moves to the next one and so forth?
I assumed that order doesn't matter if Hardware or Software should come first.
First I categorized the array into an object of Category objects using Array.prototype.reduce().
From the resultant object you can build the JSX
var data1 = [
{
id: '1',
Category: 'Hardware',
Name: 'Xtreme',
},
{
id: '123',
Category: 'Software',
Name: 'Obsolete',
},
{
id: '12345',
Category: 'Software',
Name: 'V1',
},
{
id: '1234567',
Category: 'Hardware',
Name: 'CPU',
},
];
const categorizedData = data1.reduce((acc, curr) => {
const { id, Category, Name } = curr;
if (!acc[Category]) {
acc[Category] = {
items: [],
};
}
acc[Category].items.push(Name);
return acc;
}, {});
console.log(categorizedData);
Object.keys(categorizedData).map((key, index) => {
console.log(`Category: ${key}`);
categorizedData[key].items.map((item, index) =>
console.log(`Item ${index}: ${item}`)
);
});

Map array inside of arrays reactNative

I get an array after console log my state that get data from Firebase. I want to know: can anyone help me to map array and get below details on ui. Thank You.
I tried below way, but app keep getting errors
Array [
Object {
"lists": Array [
Object {
"lists": Array [
Object {
"id": "123",
"imageUrl": "http://www.pngmart.com/files/1/Pizza-Slice-PNG-Transparent-Image.png",
"name": "Chicken Devill pizza",
"price": 700,
"size": "Medium",
},
],
"randomid": "32013408-0f48-4b15-80c4-eba3fc1fe295",
},
Object {
"lists": Array [
Object {
"id": "1234",
"imageUrl": "http://www.pngmart.com/files/1/Cheese-Pizza.png",
"name": "Cheese pork pizza",
"price": 1500,
"size": "Medium",
},
],
"randomid": "12a74805-4932-4397-b838-6773bc7e44b8",
},
],
},
]
In below code it show a error:
TypeError: undefined is not a function (near '...this.state.lists.map...')
{this.state.lists.lists.map((current, i) => (
))}
The first list here is an array not an Object. You can't call lists.lists because of this.
You will need to flatten the list or use nested map operations.
export default function App() {
const state = {
lists: [
{
lists: [
{
id: "123",
imageUrl:
"http://www.pngmart.com/files/1/Pizza-Slice-PNG-Transparent-Image.png",
name: "Chicken Devill pizza",
price: 700,
size: "Medium"
}
],
randomid: "32013408-0f48-4b15-80c4-eba3fc1fe295"
},
{
lists: [
{
id: "1234",
imageUrl: "http://www.pngmart.com/files/1/Cheese-Pizza.png",
name: "Cheese pork pizza",
price: 1500,
size: "Medium"
}
],
randomid: "12a74805-4932-4397-b838-6773bc7e44b8"
}
]
};
return (
<div className="App">
{state.lists.map((list) => {
return list.lists.map((item) => {
return <p>{item.id}</p>;
});
})}
</div>
);
}
You can find this working here: https://codesandbox.io/s/nervous-tu-u2h8v?file=/src/App.js
I also want to add some thing by myself
I done the mapping inside a mapping like this
{this.state.lists.map((current, i) => (
<View>
{current.map((current, i) => (
<Fragment>
<TouchableOpacity style={styles.card} onPress={() => this.details(current.id)}>
<Image style={styles.img} key={i} source={{uri: current.lists[0].imageUrl}}/>
<Text style={styles.txt} key={i}>{current.lists[0].name}</Text>
<Text style={styles.txt} key={i}>{current.lists[0].size}</Text>
<Text style={styles.txt} key={i}>LKR.{current.lists[0].price}</Text>
</TouchableOpacity>
</Fragment>
))}
</View>
))}

How to pass object array as props to a custom component in react native?

I have fetched some data from an API as a JSON array in componentDidMount method as below.
componentDidMount() {
return fetch('http://..someAPI../product/')
.then(res => res.json())
.then(resJson => {
this.setState({
isLoading: false,
dataSource: resJson,
});
var objects = this.state.dataSource;
for (var i = 0; i < objects.length; i++) {
console.log('Item Name: ' + objects[i].productName);
}
})
.catch(err => {
console.log(err);
});
}
In here I get console.log output as I want. Now I want to pass the array in a loop as a prop to a custom component, but it gives error.
My render method looks like this
return (
<View>
<Content>
{this.state.dataSource.map(item => {
<Product Name={item.productName} price={item.price}/>;
})}
</Content>
</View>
);
My original Json object looks like this
[
{
"category": [
"Food",
"Bread",
"Bun"
],
"_id": "1",
"productName": "Sausage bun",
"price": 70,
"details": "test product",
},
{
"category": [
"Food",
"Bread",
"Bun"
],
"_id": "2",
"productName": "Fish Pastry",
"price": 50,
"details": "test product",
}
]
I want to pass these data to display the products as a loop. How can I do this? Thank you in advance!
Since data loading is asynchronous you probably have uninitialised state.
As a safer coding practice you could something like
{this.state.dataSource && this.state.dataSource.map(item => {
return <Product Name={item.productName} price={item.price}/>;
})}
Depending on your webpack configuration , you can also use optional chaining https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining
{this.state?.dataSource?.map(item => {
<Product Name={item.productName} price={item.price}/>;
})}
Also,
initialize your state
this.state = {
dataSource: []
}

React - setState with certain index

I've been stuck for whole day and please help me to fix it.
I have a json data which like this :
[
{
"menu": "menu_1",
"icon": "icon_1",
"detail": {
"name": "name_1",
"phone": "phone_1"
}
},
{
"menu": "menu_2",
"icon": "icon_2",
"detail": {
"name": "name_2",
"phone": "phone_2"
}
},
{
"menu": "menu_3",
"icon": "icon_3",
"detail": {
"name": "name_3",
"phone": "phone_3"
}
}
]
I put them into the "data" state and My goal is I wanna change the "detail" state with certain index ( ex: state "data" with index 1 change the "detail" data )
Currently my code is :
this.setState({
data: {
...this.state.data,
detail:{
this.state.data[1].detail:{
"name": "billy",
"phone": "893823839"
}
}
}
})
That setState is clearly wanna change the state with certain index but fail..
How do I supposed to do?
I guess this is what you're looking for, we could replace an element inside an array using splice :
const index = 1;
this.setState({
data: [...this.state.data].splice(index, 1, {
...this.state.data[index],
details: { name: "billy", phone: "893823839" },
}),
});
Update: we could use slice also to make an immutable update with index :
this.setState({
data: [
...this.state.data.slice(0, index),
{
...this.state.data[index],
details: { name: "billy", phone: "893823839" },
},
...this.state.data.slice(index + 1, this.state.data.length),
],
});
could you try it ?
this is an example that i tested using splice:
const items = [{ id: 1 }, { id: 2 }, { id: 3 }];
const indexToBeModified = 1; // { id: 2 } ==> { foo: "foo", id: 2 }
items.splice(indexToBeModified, 1, { ...items[indexToBeModified], foo: "foo" });
console.log("items", items);
Here is a little modified example. It uses prevState to prevent any unwanted changes that may happen when directly interacting with this.state.
import React, { Component } from "react";
export default class App extends Component {
constructor() {
super();
this.state = {
data: [
{
menu: "menu_1",
icon: "icon_1",
detail: {
name: "name_1",
phone: "phone_1"
}
},
{
menu: "menu_2",
icon: "icon_2",
detail: {
name: "name_2",
phone: "phone_2"
}
},
{
menu: "menu_3",
icon: "icon_3",
detail: {
name: "name_3",
phone: "phone_3"
}
}
]
};
this.modifyData = this.modifyData.bind(this);
}
modifyData(index) {
this.setState((prevState) => {
prevState.data[index].detail={
name: "billy",
phone: "893823839"
};
return {
data: [prevState.data]
};
},()=>{console.log(this.state.data)});
}
render() {
return (
<button onClick={() => this.modifyData(0)}>Click to modify data</button>
);
}
}
Here is a code sandbox reference.

How to map json data with array in react native

I have array like this in react native
const data = [
{ key: 1, label: 'Service1'},
{ key: 2, label: 'Service2' },
{ key: 3, label: 'Service3' },
{ key: 4, label: 'Service4' },
{ key: 5, label: 'Service4' },
];
and json data:
"services": [
{
"id": 1,
"name": "Hotels",
},
{
"id": 2,
"name": "Embassies",
},
]
How to map id to key and name to label???
You want to fill your const data with values from JSON, correct?
Try this:
var jsonData = {
"services": [
{ "id": 1, "name": "Hotels" },
{ "id": 2, "name": "Embassies" }
]
};
var data = jsonData.services.map(function(item) {
return {
key: item.id,
label: item.name
};
});
console.log(data);
if your data like below (removed services key)
var jsonData = [
{ "id": 1, "name": "Hotels" },
{ "id": 2, "name": "Embassies" }
];
var data = jsonData.map(function(item) {
return {
key: item.id,
label: item.name
};
});
console.log(data);
i know it to much late,but i hope its helpfull for others,How to fetch the response of JSON array in react native?How to map json data with array in react native
export default class ExpenseNew extends Component {
constructor(){
super();
this.state={
PickerSelectedVal : '',
accountnameMain:[],
}
}
componentDidMount(){
var account_nam=[]
fetch('your Url', {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + your token }
})
.then((response) => response.json())
.then((customerselect) => {
// alert(JSON.stringify(customerselect))
global.customerdata = JSON.stringify(customerselect)
var customername = JSON.parse(customerdata);
//alert(JSON.stringify(customername));
for (i = 0; i < customername.cus_data.length; i++) {
var dataa = customername.cus_data[i]["account_name"];
account_nam.push(dataa)
}
this.setState({accountnameMain:account_nam});
})
.done();
}
render() {
return (
<Picker
selectedValue={this.state.PickerSelectedVal}
placeholder="Select your customer"
mode="dropdown"
iosIcon={<Icon name="arrow-down" />}
onValueChange={(itemValue, itemIndex) => this.setState({PickerSelectedVal: itemValue})} >
{this.state.accountnameMain.map((item, key)=>(
<Picker.Item label={item} value={item} key={key}/>)
)}
</Picker>
)
}
}
the above example is fetch array of data from json,and map data in to dropdown/picker,i hope its helpfull for others,if you have any query, asked from me

Resources