React Recharts- getting data from different array names - javascript

I have an app that shows a graph by date and brand. Unfortunately I'm new to react and recharts and i dont know how to get the specific data that I want.
For now I am using an area chart
as for my data
const data1 = [
{
"data1result": [
{
"brand": "brand1"
},
{
"brand": "brand2"
},
{
"brand": "brand3"
},
{
"brand": "brand4"
}
]
}
];
const data2 = [
{
"data2result": [
{
"date": "12-01",
"details": [
{
"amount": 24250,
"brand": "brand1"
},
{
"amount": 68350,
"brand": "brand2"
},
{
"amount": 60,
"brand": "brand3"
},
{
"amount": 11078,
"brand": "brand4"
}
]
},
{
"date": "12-02",
"details": [
{
"amount": 27340,
"brand": "brand1"
},
{
"amount": 16500,
"brand": "brand2"
},
{
"amount": 210,
"brand": "brand3"
},
{
"amount": 23229,
"brand": "brand4"
}
]
},
{
"date": "12-03",
"details": [
{
"amount": 24250,
"brand": "brand1"
},
{
"amount": 68350,
"brand": "brand2"
},
{
"amount": 60,
"brand": "brand3"
},
{
"amount": 11078,
"brand": "brand4"
}
]
}
]
}
];
and for my code
export default React.createClass({
render() {
return (
<ResponsiveContainer width="100%" aspect={3}>
<AreaChart width={600} height={400} data={data}
margin={{top: 10, right: 30, left: 0, bottom: 0}}>
<XAxis height={60} tick={<CustomizedAxisTick/>} dataKey="name"/>
<YAxis/>
<CartesianGrid strokeDasharray="3 3"/>
<Tooltip/>
{data1[0].data1result.map(function(c, index) {
return (
<Area type='monotone' dataKey={c.name} stroke={colors[index % colors.length]} fill={colors[index % colors.length]} fillOpacity={0.3}/>
)
})}
<Legend/>
</AreaChart>
</ResponsiveContainer>
)}
})
and output should be like this

You need to construct your data as 0-indexed array of objects.
let graphData = [
{
date: "12-01",
brand1: 24250,
brand2: 68350,
brand3: 60,
brand4: 11078,
},
{
date: "12-02",
brand1: 27340,
brand2: 16500,
brand3: 210,
brand4: 23229,
},
{
date: "12-03",
brand1: 24250,
brand2: 68350,
brand3: 60,
brand4: 11078,
}]
And your component will look like this
export default React.createClass({
_drawAreas(){
let data = this.state.data || [];
let dataSet = data[0], areaArr = [];
let count = 0, len = Object.keys(dataSet).length;
let colorCodes = ["#17607D", "#F2D8A7", "#1FCECB", "#FF9311", "#003D5C", "#F27649", "#D5CDB6", "#008C74", "#30588C", "#263138"]
for(let i in dataSet){
if(dataSet.hasOwnProperty(i) && i != 'date'){
areaArr.push(<Area type='monotone' dataKey={i} stroke={colorCodes[count]} key={`area-chart-${count}`} fill={colorCodes[count]}/>)
count++;
}
}
return areaArr;
}
render() {
return (
<ResponsiveContainer width="100%" aspect={3}>
<AreaChart width={600} height={400} data={this.state.data}
margin={{top: 10, right: 30, left: 0, bottom: 0}}>
<XAxis height={60} dataKey="date"/>
<YAxis/>
<CartesianGrid strokeDasharray="3 3"/>
<Tooltip/>
{this._drawAreas()}
<Legend/>
</AreaChart>
</ResponsiveContainer>
)} })

Related

How to Destructure JSON array>object>array

I'm trying to destructure a JSON file that looks like this:
[
{
"Bags": [
{
"id": 1,
"name": "Michael Kors Bag",
"price": 235,
"imgURL": "/imgs/03045643da82a42a4a5c86842f4b17f1.jpg"
},
{
"id": 2,
"name": "Ted Baker Bag",
"price": 495,
"imgURL": "/imgs/4c176b2fa86bdcddf74822c2501bbcac.jpg"
},
{
"id": 3,
"name": "Coach Bag",
"price": 238,
"imgURL": "/imgs/coach-jes-crossbody-signature-canvas-brown-black-59181.jpg"
},
{
"id": 4,
"name": "Kate Spade Bag",
"price": 35,
"imgURL": "/imgs/10.jpg"
}
]
},
{
"Shoes": [
{
"id": 1,
"name": "Michael Kors Bag",
"price": 235,
"imgURL": "/imgs/03045643da82a42a4a5c86842f4b17f1.jpg"
},
{
"id": 2,
"name": "Ted Baker Bag",
"price": 495,
"imgURL": "/imgs/4c176b2fa86bdcddf74822c2501bbcac.jpg"
},
{
"id": 3,
"name": "Coach Bag",
"price": 238,
"imgURL": "/imgs/coach-jes-crossbody-signature-canvas-brown-black-59181.jpg"
},
{
"id": 4,
"name": "Kate Spade Bag",
"price": 35,
"imgURL": "/imgs/10.jpg"
}
]
}
]
So that I get the name of the objects ("Bags" and "Shoes").
I'm trying to print out the results on a page based on which is which and I'm feeding in the names as strings to a Store component like so:
<Route path="/store" element={<Store merch="Bags" />} />
This is my Store.tsx file, it doesn't work at all but it's my attempt:
import storeItems from "../data/items.json";
import { Row, Col, Container } from "react-bootstrap";
import { StoreItem } from "../components/StoreItem";
import { useState } from "react";
type StoreProps = {
merch: string;
};
export function Store({ merch }: StoreProps) {
const [data, setData] = useState([]);
for (let i = 0; i < storeItems.length; i++) {
let a = Object.values(storeItems[i]);
console.log(a);
}
console.log(storeItems);
return (
<>
<Container className="mw-80 d-flex align-items-center justify-content-center p-0 flex-column mb-5">
<h1 className="m-5">Bags</h1>
<Row md={2} xs={1} lg={3} className="g-3">
{storeItems.map((item) => (
<Col>
<StoreItem key={item.id} {...item} />
</Col>
))}
</Row>
</Container>
</>
);
}
In order to get ["Bags", "Shoes"] from your storeItems you could:
const names = storeItems.flatMap(mi => Object.keys(mi));
This would get additional keys on the same object as well, so if you had:
const storeItems = [
{ "Bags": /*...*/{}, "Bags2": /*...*/{}, },
{ "Shoes": /*...*/{} },
];
then it would return [ "Bags", "Bags2", "Shoes" ]
I have to say, your data is in a pretty strange format, but I answered the question exactly as written
Also, if you want the names of all of the objects in a list, as in the name property of each object you could do something like:
const names = storeItems.flatMap(storeItem =>
Object
.values(storeItem)
.flatMap(itemList => itemList.map(item => item.name))
);
Also, if you want the names of all of the objects in the keys of an object by the name (like "Bags", or "Shoes") then you could:
const names = Object.fromEntries(storeItems.flatMap(storeItem =>
Object.entries(storeItem)
).map([k,v] => [k,v.map(i => i.name)]))
I'm not quite sure which one of these you wanted, so I included all of them (:
Edit
Looking at your code it seems as if you want to get a specific section of the data. This could be done by something like this:
const name = "Shoes";
const items = storeItems.flatMap(si => Object.entries(si))[name]
or if you know that your data is going to always have shoes first and be in the exact format then you could just do
const name = "Shoes";
const items = storeItems[1]["Shoes"];
Is this what you're trying to do?
const products = [
{
"Bags": [
{
"id": 1,
"name": "Michael Kors Bag",
"price": 235,
"imgURL": "/imgs/03045643da82a42a4a5c86842f4b17f1.jpg"
},
{
"id": 2,
"name": "Ted Baker Bag",
"price": 495,
"imgURL": "/imgs/4c176b2fa86bdcddf74822c2501bbcac.jpg"
},
{
"id": 3,
"name": "Coach Bag",
"price": 238,
"imgURL": "/imgs/coach-jes-crossbody-signature-canvas-brown-black-59181.jpg"
},
{
"id": 4,
"name": "Kate Spade Bag",
"price": 35,
"imgURL": "/imgs/10.jpg"
}
]
},
{
"Shoes": [
{
"id": 1,
"name": "Michael Kors Bag",
"price": 235,
"imgURL": "/imgs/03045643da82a42a4a5c86842f4b17f1.jpg"
},
{
"id": 2,
"name": "Ted Baker Bag",
"price": 495,
"imgURL": "/imgs/4c176b2fa86bdcddf74822c2501bbcac.jpg"
},
{
"id": 3,
"name": "Coach Bag",
"price": 238,
"imgURL": "/imgs/coach-jes-crossbody-signature-canvas-brown-black-59181.jpg"
},
{
"id": 4,
"name": "Kate Spade Bag",
"price": 35,
"imgURL": "/imgs/10.jpg"
}
]
}
]
const getProductsByKey = key => products
.filter(product => product.hasOwnProperty([key]))
.flatMap(obj => obj[key])
console.log(getProductsByKey('Shoes'))
The output of the above code would be:
[
{
id: 1,
name: 'Michael Kors Bag',
price: 235,
imgURL: '/imgs/03045643da82a42a4a5c86842f4b17f1.jpg'
},
{
id: 2,
name: 'Ted Baker Bag',
price: 495,
imgURL: '/imgs/4c176b2fa86bdcddf74822c2501bbcac.jpg'
},
{
id: 3,
name: 'Coach Bag',
price: 238,
imgURL: '/imgs/coach-jes-crossbody-signature-canvas-brown-black-59181.jpg'
},
{ id: 4, name: 'Kate Spade Bag', price: 35, imgURL: '/imgs/10.jpg' }
]
Please note that the supplied data is incorrect as the items under the key "Shoes" are apparently bags.
I'll explain the why and how of my code. First off, I wanted to make a function that could take any key as an argument. Today we have 'Bags' and 'Shoes', but tomorrow we may have more keys. Therefore, I didn't want to propose a solution that would involve "hard-coded" keys.
Once we have the key, we can use Array.prototype.filter to find the object containing the items we want. In the data we are provided with, 'Bags' and 'Shoes' are keys, not values. Hence why I used product.hasOwnProperty([key]) in the callbackFn. Note the use of the square brackets as we are searching for the value of a dynamic variable named key, not the actual string 'key'. Next we use Array.protoype.flatMap to get to the part of each object that we want, which is the array of items. We use .flapMap here to avoid the nested array that would normally result by chaining filter and map to the data.
For getting the shoes you can use this:
storeItems[1]["shoes"]
And for getting the bags you can use this:
storeItems[0]["bags"]
So, in the return expression in your attempt code, instead of this:
return (
<>
<Container className="mw-80 d-flex align-items-center justify-content-center p-0 flex-column mb-5">
<h1 className="m-5">Bags</h1>
<Row md={2} xs={1} lg={3} className="g-3">
{storeItems.map((item) => (
<Col>
<StoreItem key={item.id} {...item} />
</Col>
))}
</Row>
</Container>
</>);
use this (for bags):
return (
<>
<Container className="mw-80 d-flex align-items-center justify-content-center p-0 flex-column mb-5">
<h1 className="m-5">Bags</h1>
<Row md={2} xs={1} lg={3} className="g-3">
{storeItems[0]["bags"].map((item) => (
<Col>
<StoreItem key={item.id} {...item} />
</Col>
))}
</Row>
</Container>
</>);
You can use:
a combination of Array.map and Object.keys to get an array with available categories from storeItems object
Array.find to get the products for a given merch category.
const storeItems = [
{
"Bags": [
{
"id": 1,
"name": "Michael Kors Bag",
"price": 235,
"imgURL": "/imgs/03045643da82a42a4a5c86842f4b17f1.jpg"
},
{
"id": 2,
"name": "Ted Baker Bag",
"price": 495,
"imgURL": "/imgs/4c176b2fa86bdcddf74822c2501bbcac.jpg"
},
{
"id": 3,
"name": "Coach Bag",
"price": 238,
"imgURL": "/imgs/coach-jes-crossbody-signature-canvas-brown-black-59181.jpg"
},
{
"id": 4,
"name": "Kate Spade Bag",
"price": 35,
"imgURL": "/imgs/10.jpg"
}
]
},
{
"Shoes": [
{
"id": 1,
"name": "Michael Kors Bag",
"price": 235,
"imgURL": "/imgs/03045643da82a42a4a5c86842f4b17f1.jpg"
},
{
"id": 2,
"name": "Ted Baker Bag",
"price": 495,
"imgURL": "/imgs/4c176b2fa86bdcddf74822c2501bbcac.jpg"
},
{
"id": 3,
"name": "Coach Bag",
"price": 238,
"imgURL": "/imgs/coach-jes-crossbody-signature-canvas-brown-black-59181.jpg"
},
{
"id": 4,
"name": "Kate Spade Bag",
"price": 35,
"imgURL": "/imgs/10.jpg"
}
]
}
]
// Get the values for merch types
const categories = storeItems.map((entry) => Object.keys(entry)[0])
console.log(categories)
// Find the products for a given merch
const merch = 'Shoes'
const products = storeItems.find((entry) => entry[merch])[merch]
console.log(products)

React object to array to print out on frontend using .map

i actually have return 2 types of result from 1 API call
{
"data1": [
{
"item_name": "item 4",
"price_updated_date": "2022-04-14T08:05:16.339Z",
"item_img_id": "https://testing.jpg",
"set_name": "2017",
"set_tag": "mm3",
"rarity": "rare",
"price_normal": 34.99,
"price_foil": 54.99
},
],
"data2": [
{
"item_condition": "NM",
"item_img": "https://test.jpg",
"item_name": "item 1",
"item_set": "ZEN",
"item_language": "JP",
"item_type": "Non Foil",
"item_price": "¥ 4,580",
"item_qty": 9,
"other_condition": {
"SP": {
"qty": 1,
"price": "¥ 3,670"
},
"MP": {
"qty": 1,
"price": "¥ 3,210"
}
}
},
{
"item_condition": "NM",
"item_img": "https://0010.jpg",
"item_name": "item 3",
"item_set": "ZNE",
"item_language": "JP",
"item_type": "Non Foil",
"item_price": "¥ 8,000",
"item_qty": 6,
"other_condition": {
"MP": {
"qty": 1,
"price": "¥ 6,400"
}
}
},
]
}
from the return, they are all Object, so i need to make a conversion to Array in order to print them out on my frontend with .map so i use this
const convertObjToArr = (responseObj) => {
let arr = []
Object.keys(responseObj).forEach(function(key) {
arr.push(responseObj[key]);
});
return arr
}
convertObjToArr(data.data1)
convertObjToArr(data.data2)
however, my data2 has another object inside it as well call "other_condition" which is not converting to Array and is still in Object. When i tried to display it with .map, it gives me error. In this case, how can i handle that object to array? is there any way to convert all of them into Array regardless how many nested object i have in one data?
Does this help?
const renderThisItem = itm => {
/*console.log(
'itm: ', itm,
'typeof: ', typeof itm,
'keys: ', Object.keys(itm)
);*/
if (itm) {
if (typeof itm === 'string' || typeof itm === 'number') {
return (<div>{itm},</div>);
} else if (Array.isArray(itm)) {
return (
<div>[{
itm.map(it => renderThisItem(it))
}],</div>
)
} else if (Object.keys(itm).length > 0) {
return (
<div>{"{"} {
Object.entries(itm)
.map(([k, v]) => (
<div>
<div class="val">{k}: {renderThisItem(v)}</div>
</div>
))
} {"},"}</div>
)
}
};
};
const Thingy = ({ dataObj, ...props }) => {
return (
<div>{renderThisItem(dataObj)}</div>
);
};
const rawData = {
"data1": [
{
"item_name": "item 4",
"price_updated_date": "2022-04-14T08:05:16.339Z",
"item_img_id": "https://testing.jpg",
"set_name": "2017",
"set_tag": "mm3",
"rarity": "rare",
"price_normal": 34.99,
"price_foil": 54.99
},
],
"data2": [
{
"item_condition": "NM",
"item_img": "https://test.jpg",
"item_name": "item 1",
"item_set": "ZEN",
"item_language": "JP",
"item_type": "Non Foil",
"item_price": "¥ 4,580",
"item_qty": 9,
"other_condition": {
"SP": {
"qty": 1,
"price": "¥ 3,670"
},
"MP": {
"qty": 1,
"price": "¥ 3,210"
}
}
},
{
"item_condition": "NM",
"item_img": "https://0010.jpg",
"item_name": "item 3",
"item_set": "ZNE",
"item_language": "JP",
"item_type": "Non Foil",
"item_price": "¥ 8,000",
"item_qty": 6,
"other_condition": {
"MP": {
"qty": 1,
"price": "¥ 6,400"
}
}
},
]
};
ReactDOM.render(
<div>
DEMO
<Thingy dataObj={rawData} />
</div>,
document.getElementById('rd')
);
.val { display: flex; }
<div id="rd" />
<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>

Selection of product options as a combination of options

I am trying to achieve the following for my project.
combinations
my data structure for options and combinations as following:
"options": [
{
"id": "96ce60e9-b09b-4cf6-aeca-83f75af9ef4b",
"position": 0,
"name": "Color",
"values": [
{
"id": "9056c8d4-a950-43bc-9477-283a8954285b",
"name": "",
"label": "RED"
},
{
"id": "35c7cc36-2ff4-4eb6-bc96-03cc3ea04751",
"name": "",
"label": "BLACK"
}
]
},
{
"id": "c657ee5b-57bb-4265-8113-4fefca71f785",
"position": 1,
"type": "",
"name": "SIZE",
"values": [
{
"id": "494196ec-5857-48b1-be35-ffc785e5020d",
"name": "",
"label": "LARGE"
},
{
"id": "389255cb-0c88-45e8-a1dc-6ce9fedbd98c",
"name": "",
"label": "SMALL"
}
]
}
],
Variants:
"combinations": [
{
"id": "84468215-d6b5-455e-bfdc-6a03cfe49d21",
"ids": [
"9056c8d4-a950-43bc-9477-283a8954285b",
"494196ec-5857-48b1-be35-ffc785e5020d"
],
"quantity": "12",
"code": 0,
"barcode": 0,
"sellPrice": 0
},
{
"id": "4c84ec32-bf4c-463d-9872-bc6a9794e7ba",
"ids": [
"9056c8d4-a950-43bc-9477-283a8954285b",
"389255cb-0c88-45e8-a1dc-6ce9fedbd98c"
],
"quantity": "12",
"code": 0,
"barcode": 0,
"sellPrice": 0
},
{
"id": "76a3ccdd-c8b4-44dc-99bf-a83a65dc0fe0",
"ids": [
"35c7cc36-2ff4-4eb6-bc96-03cc3ea04751",
"494196ec-5857-48b1-be35-ffc785e5020d"
],
"quantity": 0,
"code": 0,
"barcode": 0,
"sellPrice": 0
},
{
"id": "ec8c8cec-d2a7-4c90-8c9b-12cfeb78d0f6",
"ids": [
"35c7cc36-2ff4-4eb6-bc96-03cc3ea04751",
"389255cb-0c88-45e8-a1dc-6ce9fedbd98c"
],
"quantity": 0,
"code": 0,
"barcode": 0,
"sellPrice": 0
}
],
I've never worked on something like that before. For each combination for example (RED/SMALL), I am storing the 'RED' option id and 'Small' option id.
till now I've tried the following logic, where I want to compare between ids to get the combination as object then process the order as I want:
{product.options.map((opt) => (
<div key={opt.id}>
<h4 className="font-bold">{opt.name}</h4>
<ul className="flex flex-row justify-evenly p-2 px-10 gap-3">
{opt.values.map((val) => (
<li key={val.id}>
<button
key={val.id}
style={{
backgroundColor: val.name,
borderRadius: '50%',
border: '1px solid #C9C9C9',
boxShadow: '0px 0px 5px #C9C9C9',
alignContent: 'center',
alignItems: 'center',
justifyContent: 'center',
width: '30px',
height: '30px',
}}
type="button"
className={`${
comboIds[0] === val.id
? 'border-2 border-black '
: 'bg-white'
} `}
onClick={() => {
comboIds.push(val.id);
let comboTitle = [];
comboTitle.push(val.name);
product.combinations.find((combo) => {
if (combo.ids.join('') === comboIds.join('')) {
return availableCombinations.push({
...combo,
title: comboTitle,
});
} else {
return null;
}
});
console.log(availableCombinations);
}}
>
{opt.type === 'color' ? ' ' : val.name}
</button>
</li>
))}
When user pressed a color for example, I want only available sizes show up and I mean by available sizes is to check for quantity of the pressed color with available sizes.
I appreciate any help. Thank you!

Reduce array differentiating by category in reactjs

I'm developing an app in reactjs and I have the array:
array = [
{
"id": 1,
"categoryId": 2,
"period": "202101",
"type": "A",
"price": 100,
"discount": 0
},
{
"id": 2,
"categoryId": 2,
"period": "202102",
"type": "B",
"price": 300,
"discount": 20
},
{
"id": 3,
"categoryId": 2,
"period": "202103",
"type": "B",
"price": 200,
"discount": 70
},
{
"id": 4,
"categoryId": 2,
"period": "202104",
"type": "A",
"price": 100,
"discount": 50
},
]
and I need to reduce it to show it as the table:
what I did to show the detail of the prices per period:
const items = array.reduce((acc, e) => {
if (!acc[e["categoryId"]]) {
acc[e["categoryId"]] = {
[e["period"]]: e["price"]
}
} else {
acc[e["categoryId"]][e["period"]] = e["price"]
}
return acc
}, {})
const periods = [...new Set(Object.keys(items).map(i => Object.keys(items[i])).flat())]
thead:
<tr>{dates.map(date => <th>{date}</th>)}</tr>
tbody:
Object.keys(items).map((item) => {
return (
<tr>
<td>{item}</td>
{periods.map((period) => <td>{items[item][period] || ''}</td>)}
</tr>
)
})
but it is only showing the price for each period. I need to show discount and type as well.
What changes are needed, any suggestion?
I think I didn't understand your needs well,
but this is what I did according to your description:
array.reduce((acc, curr) => {
if (!acc[curr["categoryId"]]) {
acc[curr["categoryId"]] = {
[curr["period"]]: {
"price": curr["price"],
"type": curr["type"],
"discount": curr["discount"]
}
}
} else {
acc[curr["categoryId"]][curr["period"]] = {
"price": curr["price"],
"type": curr["type"],
"discount": curr["discount"]
}
}
return acc;
}, {})
And the result of this reduce is:
{
"2": {
"202101": {
"price": 100,
"type": "A",
"discount": 0
},
"202102": {
"price": 300,
"type": "B",
"discount": 20
},
"202103": {
"price": 200,
"type": "B",
"discount": 70
},
"202104": {
"price": 100,
"type": "A",
"discount": 50
}
}
}
what you are looking for is grouping the items in arrays and display them.:
let array = [
{
id: 1,
categoryId: 2,
period: "202101",
type: "A",
price: 100,
discount: 0
},
{
id: 2,
categoryId: 2,
period: "202102",
type: "B",
price: 300,
discount: 20
},
{
id: 3,
categoryId: 2,
period: "202103",
type: "B",
price: 200,
discount: 70
},
{
id: 4,
categoryId: 2,
period: "202104",
type: "A",
price: 100,
discount: 50
}
];
let dates = array.map((e) => <th>{e.period}</th>);
let prices = array.map((e) => <td>{e.price}</td>);
let discounts = array.map((e) => <td>{e.discount}</td>);
let types = array.map((e) => <td>{e.type}</td>);
function App() {
return (
<div className="App">
<table>
<tr>{dates}</tr>
<tr>{prices}</tr>
<tr>{discounts}</tr>
<tr>{types}</tr>
</table>
</div>
);
}
ReactDOM.render(<App/>,document.getElementById('root'))
<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>

I dont know how to use map in this situation

I wrote the contents of this JSON to the array "heroes", but I don't know how to get "damage", "basicAttack.category" and "specialAttack.category" for mapping. I tried to solve this problem but unfortunately I don't know how.
{
"id": 20,
"name": "Warrior",
"skills": [
{
"id": 1,
"basicAttack": {
"id": 2,
"name": "Hit1",
"category": "weakAttack"
},
"specialAttack": {
"id": 16,
"name": "Special1",
"category": "spellAttack"
},
"damage": 200
},
{
"id": 2,
"basicAttack": {
"id": 3,
"name": "Hit2",
"category": "rangeAttack"
},
"specialAttack": {
"id": 17,
"name": "Special2",
"category": "fightAttack"
},
"damage": 100
}
]
}
and this is my way of mapping and what data I'm trying to get
const item = this.state.heroes.skills.map(item => {
/*i dont have idea how map
<p>{item.damage}</p>
<p>{item.specialAttack.cathegory} + {item.basicAttack.category}</p>
*/
})
Just map over the heroes.skills and you will find the result how to access the value
var heroes ={
"id": 20,
"name": "Warrior",
"skills": [
{
"id": 1,
"basicAttack": {
"id": 2,
"name": "Hit1",
"category": "weakAttack"
},
"specialAttack": {
"id": 16,
"name": "Special1",
"category": "spellAttack"
},
"damage": 200
},
{
"id": 2,
"basicAttack": {
"id": 3,
"name": "Hit2",
"category": "rangeAttack"
},
"specialAttack": {
"id": 17,
"name": "Special2",
"category": "fightAttack"
},
"damage": 100
}
]
}
heroes.skills.map(hero=>{
console.log("damage...........",hero.damage)
console.log("basicAttack.category.........",hero.basicAttack.category)
console.log("specialAttack.category........",hero.specialAttack.category)
})
if you want to render then you have to return it and then render
const heroesDiv = this.state.heroes.skills.map((hero) => (
<>
<p>{item.damage}</p>
<p>{item.specialAttack.category} + {item.basicAttack.category}</p>
</>
))
this.state.heroes.skills.map((item) => {
return `<div><p>${item.damage}</p><p>${item.specialAttack.category} ${item.basicAttack.category}</p></div>`
})
let data = {
"id": 20,
"name": "Warrior",
"skills": [
{
"id": 1,
"basicAttack": {
"id": 2,
"name": "Hit1",
"category": "weakAttack"
},
"specialAttack": {
"id": 16,
"name": "Special1",
"category": "spellAttack"
},
"damage": 200
},
{
"id": 2,
"basicAttack": {
"id": 3,
"name": "Hit2",
"category": "rangeAttack"
},
"specialAttack": {
"id": 17,
"name": "Special2",
"category": "fightAttack"
},
"damage": 100
}
]
}
this is how you can map
return (
<div>
{data.skills.map(item=>
<div key={item.id}>
<h3>{item.id}: {item.basicAttack.name}-{item.basicAttack.category}, {item.specialAttack.name}-{item.specialAttack.category}</h3>
</div>)}
</div>
)
const item = this.state.heroes.skills.map(item => {
return(
<React.Fragment key={item.id}>
<p>{item.damage}</p>
<p>{item.specialAttack.id}</p>
<p>{item.basicAttack.id}</p>
<p>{item.damage}</p>
<React.Fragment>
)
})
You can use JSON.parse to parse the json data and you can easily map as shown in the working snippet below.
var data='{"id":20,"name":"Warrior","skills":[{"id":1,"basicAttack":{"id":2,"name":"Hit1","category":"weakAttack"},"specialAttack":{"id":16,"name":"Special1","category":"spellAttack"},"damage":200},{"id":2,"basicAttack":{"id":3,"name":"Hit2","category":"rangeAttack"},"specialAttack":{"id":17,"name":"Special2","category":"fightAttack"},"damage":100}]}';
var jsondata=JSON.parse(data);
console.log(jsondata.skills[0].damage);
console.log(jsondata.skills[0].basicAttack['category']);
console.log(jsondata.skills[0].specialAttack['category']);
You can do it as this
const item = this.state.heroes.skills.map(item => {
return (
<React.Fragment>
<p>{item.damage}</p>
<p>{item.specialAttack.category} + {item.basicAttack.category}</p>
</React.Fragment>
);
})
Hope it helps

Categories