How to get array format value in json using reactjs? - reactjs

I added my coding's for how to create state like at the end of this question above coding's are i will try but am not able to create like that state.
This is my json format coding to get through
"Results": {
"Piechart":[{
"labels": ["Under 18", "Age 18-54", "Age 55+"],
"datasets": [{
"data": [2000, 4000, 2850],
"backgroundColor": ["red", "blue", "green"]
}]
}]
}
Here is my React Code
this.state = {labels: [], datasets: []};
componentDidMount() {
this.pieChart().then(result => {
this.setState({diagramData: result.pieDiagramLabel});
}).catch(err => console.error(err));
}
async pieChart() {
let pieChart = await import('../data/result_log.json');
console.log(pieChart[0].Results.Piechart);
return {
pieDiagramLabel: pieChart[0].Results.Piechart.labels
}
}
How to get both label and datasets? And how to set into state like below format
this.state= {
"labels": ["Under 18", "Age 18-54", "Age 55+"],
"datasets": [{
"data": [2000, 4000, 2850],
}]
}

You can try like this
data.json
{
"Piechart": [
{
"labels": ["Under 18", "Age 18-54", "Age 55+"],
"datasets": [
{
"data": [2000, 4000, 2850],
"backgroundColor": ["red", "blue", "green"]
}
]
}
]
}
App.js
import React from "react";
import Results from "./data.json";
export default class App extends React.Component {
state = {
labels: [],
datasets: []
};
componentDidMount() {
this.setState({
labels: Results.Piechart[0].labels,
datasets: Results.Piechart[0].datasets
});
}
render() {
const { labels, datasets } = this.state;
return (
<div className="App">
{labels.map((label, index) => (
<p key={index}>{label}</p>
))}
<hr />
{datasets.map((data, index) => (
<p key={index}>{data.backgroundColor}</p>
))}
</div>
);
}
}
Live working demo https://codesandbox.io/s/fetch-local-json-6bq4m

Related

How to search and filter in array of objects on setState

I'm trying to create a search based on an array of objects with react which data is in this format:
const data = [
{"category 1" : [
{
"name": "Orange",
"desc": "juice, orange, Water"
},
{
"name": "Ananas",
"desc": "juice, ananas, water"
}
]
},
{"category 2" : [
{
"name": "Banana Split",
"desc": "Banana, ice cream, chocolat, topping",
"allergens": "nuts"
},
{
"name": "Mango Sticky Rice",
"desc": "Mango, rice, milk",
"allergens": ""
}
]
}
]
I stored this data inside useState declaration to be able to render accordingly on data chnage:
const [filteredBySearch, setFilteredBySearch] = useState(data)
I have an input where we can type anything and set inside useState declaration.
Goal:
If I type in my input:
"Jui"
Output should be:
console.log(filteredBySearch)
/* output:
[
{"category 1" : [
{
"name": "Orange",
"desc": "juice, orange, Water"
},
{
"name": "Ananas",
"desc": "juice, ananas, water"
}
]
},
{"category 2" : []
}
]*/
Exemple 2:
If I type in my input:
"Orange banana"
Output should be:
console.log(filteredBySearch)
/* output: [
{"category 1" : [
{
"name": "Orange",
"desc": "juice, orange, Water"
}
]
},
{"category 2" : [
{
"name": "Banana Split",
"desc": "Banana, ice cream, chocolat, topping",
"allergens": "nuts"
}
]
}
]*/
I've try creating a new object with map and filter and set it with setFilteredBySearch, but I can't get anything, even creating this new object.
This the full component:
import Card from '../components/Card'
import React, { useState } from 'react';
export default function IndexPage({ data, search }) {
//search is the result of input value set on a useState
//Filter categoriesFoods by search
const [FilteredBySearch, setFilteredBySearch] = useState(data)
return (
<div className="main-content">
<div className="card-container">
{
FilteredBySearch.map(function(el, i) {
return (
<div key={i}>
<h2 className="category" id={Object.keys(el)}>{Object.keys(el)}</h2>
{
el[Object.keys(el)].map (function(itm,index){
return <Card key={index} infoItem={itm}/>
})
}
</div>
)
})
}
</div>
<style jsx>{`...`}</style>
</div>
)}
Any idea for me ?
Thanks a lot for your guidance!
I think this is what you are looking for. I have created below utilities for filtering as per your requirement.
const dataObj = [
{
'category 1': [
{
name: 'Orange',
desc: 'juice, orange, Water',
},
{
name: 'Ananas',
desc: 'juice, ananas, water',
},
],
},
{
'category 2': [
{
name: 'Banana Split',
desc: 'Banana, ice cream, chocolat, topping',
allergens: 'nuts',
},
{
name: 'Mango Sticky Rice',
desc: 'Mango, rice, milk',
allergens: '',
},
],
},
]
const checkIfInputMatches = (input, desc) => input.toLowerCase().split(" ").some(o => desc.toLowerCase().includes(o))
const filterByInput = (data, input) => {
let finalResult = [];
data.forEach(d => {
let keys = Object.keys(d);
let values = Object.values(d);
finalResult = [...finalResult, ...values.map((obj, index) => {
let result = obj.filter(o => checkIfInputMatches(input, o.desc))
return {[keys[index]]: result}
})]
})
return finalResult
}
console.log(filterByInput(dataObj, 'JUI'))
console.log(filterByInput(dataObj, "orange"))
console.log(filterByInput(dataObj, "rice"))
console.log(filterByInput(dataObj, "Orange banana"))
Hope this helps.

How to use FetchAPI nested Arrays of same object

I am trying to show menu where it can have parent child relationship, with flat structure it is working fine but with nested objects not able to do it.
The below is the JSON and reactJS code.
JSON -
{
"data": [
{
"to": "#a-link",
"icon": "spinner",
"label": "User Maintenance"
},
{
"content": [
{
"to": "#b1-link",
"icon": "apple",
"label": "System Controls"
},
{
"to": "#b2-link",
"icon": "user",
"label": "User Maintenance"
}
],
"icon": "gear",
"label": "System Preferences"
},
{
"to": "#c-link",
"icon": "gear",
"label": "Configuration"
}
]
}
ReactJS code -
export default class MenuComponent extends Component {
constructor() {
super();
this.state = {}
}
componentDidMount(){
fetch('http://localhost:8084/Accounting/rest/v1/company/menu?request=abc')
.then(response => response.json())
.then(parsedJSON => parsedJSON.data.map(menu => (
{
to: `${menu.to}`,
icon: `${menu.icon}`,
label: `${menu.label}`
// content: `${menu.content}`
}
)))
.then(content => this.setState({
content
}))
}
render() {
console.log('333');
console.log(this.state.content);
return (
<MetisMenu content={this.state.content} activeLinkFromLocation />
)
}
}
In JSON you can see the 'System Preference' has nested content.
Try this code
class MenuComponent extends Component {
constructor() {
super();
this.state = {
content : []
}
}
componentDidMount(){
fetch('http://localhost:8084/Accounting/rest/v1/company/menu?request=abc')
.then(response => response.json())
.then(parsedJSON => parsedJSON.data.map(menu => (
{
to: `${menu.to}`,
icon: `${menu.icon}`,
label: `${menu.label}`
// content: `${menu.content}`
}
)))
.then(content => this.setState({
content
}))
}
render() {
const {content} = this.state
if(content === undefined){
return <div>Content not found</div>;
}
if(content.length === 0){
return <div>Loading</div>;
}
return (
<MetisMenu content={content} activeLinkFromLocation />
)
}
}
export default MenuComponent

Pass an items prop with the items within the category key

I can't seem to pass certain items into an item prop if they relate to the category that I am looping through
I have a JSON like this:
{
"Categories": [
{
"Name": "Music",
},
{
"Name": "Comedy",
},
{
"Name": "Sport",
},
{
"Name": "Family",
},
],
"Items": [
{
"Name": "Dolly Parton",
"NameId": "dolly-parton",
"Category": "Music",
},
{
"Name": "Cee Lo Green",
"NameId": "cee-lo-green",
"Category": "Music",
},
{
"Name": "Take That",
"NameId": "take-that",
"Category": "Music",
},
{
"Name": "Football",
"NameId": "football",
"Category": "Sport",
},
{
"Name": "Hockey",
"NameId": "hockey",
"Category": "Sport",
}
]
}
I'm looping through all the categories and then printing them into a list while trying to only pass items that relate to that category in an items prop. I have the code below but it is passing all my data to each element and I'm not sure why.
class CategoryItems extends Component {
constructor(props) {
super(props);
}
state = {
items: this.props.items,
categories: this.props.categories,
};
render() {
const items = this.state.items;
return (
<section className="category-wrapper">
<div className="container">
<div className="category-wrapper__inner">
{this.state.categories.map((category, index) => (
<CategoryItem
key={category.Name}
items={items.map((item, index) => {
item.Category === category.Name ? item : '';
})}
/>
))}
</div>
</div>
</section>
);
}
}
All the data is there and in the react dev-tools it says each element has 667 items but I know there should only be 7 items on the sports category.
Apply a filter instead of a map.
<CategoryItem
key={category.Name}
items={items.filter(i => item.Category === category.Name)}
/>
You can try this ,
class CategoryItems extends Component {
constructor(props) {
super(props);
}
state = {
items: this.props.items,
categories: this.props.categories,
};
render() {
const items = this.state.items;
const renderList = this.state.categories.reduce((total, category) => {
const list = items.filter(item => item.Category === category.Name);
if(list.length > 0){
total.push(<CategoryItem
key={category.Name}
items={list}
/>);
}
return total
},[])
return (
<section className="category-wrapper">
<div className="container">
<div className="category-wrapper__inner">
{renderList}
</div>
</div>
</section>
);
}
}

Rendering a nested object state

This problem is giving me a huge headache so any help is welcome :)
In this component, I'm making 2 axios calls to different APIs: one for freegeoip and one for openweathermap. I'm storing the data in the currentCity state, which is an object with 2 keys, location and weather. The idea is that the app detects your current location (using freegeoip) and renders location name and weather data (using openweathermap).
I'm positive it's storing the state properly as console logs have confirmed. I can render the location data for currentCity state, but can't seem to render the weather data for currentCity state.
renderCurrentCity(city) {
console.log('state3:', this.state.currentCity);
console.log([city.weather.main]);
return(
<div>
<li>{city.location.city}, {city.location.country_name}</li> // Working
<li>{city.weather.main.temp}</li> // Not working
</div>
)
}
The console error I get:
Uncaught (in promise) TypeError: Cannot read property '_currentElement' of null
currentCity.location JSON:
{
"ip": // hidden,
"country_code": "FR",
"country_name": "France",
"region_code": "GES",
"region_name": "Grand-Est",
"city": "Reims",
"zip_code": "",
"time_zone": "Europe/Paris",
"latitude": 49.25,
"longitude": 4.0333,
"metro_code": 0
}
currentCity.weather JSON:
{
"coord": {
"lon": 4.03,
"lat": 49.25
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}
],
"base": "stations",
"main": {
"temp": 283.15,
"pressure": 1011,
"humidity": 43,
"temp_min": 283.15,
"temp_max": 283.15
},
"visibility": 10000,
"wind": {
"speed": 3.1,
"deg": 350
},
"clouds": {
"all": 0
},
"dt": 1493127000,
"sys": {
"type": 1,
"id": 5604,
"message": 0.1534,
"country": "FR",
"sunrise": 1493094714,
"sunset": 1493146351
},
"id": 2984114,
"name": "Reims",
"cod": 200
}
Rest of code:
import React, { Component } from 'react';
import axios from 'axios';
import WeatherList from './weatherlist';
import SearchBar from './searchbar';
const API_KEY = '95108d63b7f0cf597d80c6d17c8010e0';
const ROOT_URL = 'http://api.openweathermap.org/data/2.5/weather?'
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
cities: [],
errors: '',
currentCity: {
location: {},
weather: {}
}
};
this.currentCity();
this.renderCurrentCity = this.renderCurrentCity.bind(this);
}
citySearch(city) {
const url = `${ROOT_URL}&appid=${API_KEY}&q=${city}`;
axios.get(url)
.then(response => {
const citiesArr = this.state.cities.slice();
this.setState({
cities: [response.data, ...citiesArr],
errors: null
});
})
.catch(error => {
this.setState({
errors: 'City not found'
})
})
}
currentCity() {
var city;
var country;
axios.get('http://freegeoip.net/json/')
.then(response => {
const lat = response.data.latitude;
const lon = response.data.longitude;
city = response.data.city;
country = response.data.country_name;
const url = `${ROOT_URL}&appid=${API_KEY}&lat=${lat}&lon=${lon}`;
const state = this.state.currentCity;
console.log('state1:',state);
this.setState({
currentCity: { ...state, location: response.data }
});
console.log(url);
axios.get(url)
.then(city => {
const state = this.state.currentCity;
console.log('state2:', state);
this.setState({
currentCity: { ...state, weather: city.data }
});
})
})
}
renderCurrentCity(city) {
console.log('state3:', this.state.currentCity);
console.log([city.weather.main]);
return(
<div>
<li>{city.location.city}, {city.location.country_name}</li>
<li>{city.weather.main.temp}</li>
</div>
)
}
render() {
return (
<div className={this.state.cities == false ? 'search': 'search-up'}>
<h1>What's the weather today?</h1>
<ul className='list-unstyled text-center'>
{this.renderCurrentCity(this.state.currentCity)}
</ul>
<SearchBar
onSearchSubmit={this.citySearch.bind(this)}
errors={this.state.errors} />
{this.state.cities == false ? null : <WeatherList cities={this.state.cities} />}
</div>
)
}
}
You are spreading your whole state when your receive the weather data:
this.setState({
currentCity: { ...state, weather: city.data }
});
it should be:
this.setState({
currentCity: { ...state.currentCity, weather: city.data }
});

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