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!
Related
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)
I need a helping hand. I got a little lost in my code to set up a condition.
Basically I want to set up a checkbox that will look for the stock of a product. My array of product information is stored in this.state.displayArray.
If the product is in stock, so if this.state.displayArray.stock> 0 the checkbox is checked.
actually it sounds simple like that and i think it is but i need a little helping hand to make sure i do it right, I don't know where to add the condition, in the function or directly in the checkbox.
Thanks for your help.
export default class Stock extends Component {
constructor(props) {
super(props);
this.state = {
stock : true,
}
};
initListData = async () => {
let list = await getProducts(1);
if (list) {
this.setState({
displayArray: list,
loadMoreVisible: (list.length >= 15 ? true : false),
currentPage: 2
});
console.log(this.state.displayArray)
}
};
async UNSAFE_componentWillMount() {
this.initListData();
console.log(this.state.displayArray)
}
render() {
return (
<View style={styles.container}>
<View pointerEvents="none" style={{ flexDirection: 'row', alignItems:'center', justifyContent:'center'}}>
<CheckBox
value={this.state.stock}
/>
<Text style={{marginTop: 5}}>Stock</Text>
</View>
</View>
);
}
}
displayArray: (for now it's a flight but it will change, I have someone working on API)
Array [ Object {
"cost": 0,
"created_at": "2020-12-14T15:54:50Z",
"custom_fields": Object {
"_161_": "4137",
"_162_": "48",
"_163_": "10926",
"_164_": "0",
"_165_": "FLY",
"_166_": "2020-12-14T14:54:37.737Z",
"_167_": "2020-12-31T14:54:37.737Z",
"_168_": "0",
"_171_": "0",
"_300_": "412:00",
"_301_": "45.725556|5.081111",
"_302_": "-27.7078990936|-67.0951004028",
"_303_": "Lyon Saint-Exupéry Airport",
"_304_": "Londres/Belén Airport",
"_310_": "60",
},
"description": "",
"family_id": 0,
"id": 1061,
"incl_tax": 0,
"is_visible": 1,
"name": "Lyon Saint-Exupéry Airport (14/12/2020 à 15:54) > Londres/Belén Airport (31/12/2020 à 15:54)",
"photo": "",
"quantity": 0,
"reference": "",
"stock_status": "1",
"tax_rate_id": 0,
"unit": "",
"updated_at": "2020-12-14T15:54:50Z",
"weight": 0, }, Object {
"cost": 0,
"created_at": "2020-11-15T01:38:08Z",
"custom_fields": Object {
"_161_": "1373",
"_162_": "30",
"_163_": "4680",
"_164_": "0",
"_165_": "FLY",
"_166_": "2020-11-21T00:37:00.000Z",
"_167_": "2020-11-29T00:37:00.000Z",
"_168_": "0",
"_171_": "0",
"_300_": "190:00",
"_301_": "43.6539083949|-79.65785399079999",
"_302_": "-22.285699844399996|-62.7136993408",
"_303_": "Tarten Heliport",
"_304_": "Santa Victoria Airport",
"_310_": "-480",
},
"description": "",
"family_id": 0,
"id": 896,
"incl_tax": 0,
"is_visible": 1,
"name": "Tarten Heliport (2020-11-21 at 16:37) > Santa Victoria Airport (2020-11-29 at 16:37)",
"photo": "",
"quantity": 0,
"reference": "",
"stock_status": "1",
"tax_rate_id": 0,
"unit": "FLY",
"updated_at": "2020-11-15T01:38:08Z",
"weight": 0, }, ]
Have anyone ideas how I can filter data by "type" checking a custom "checkbox"?
I have response from API like this
"notifications": [
{
"id": 255,
"type": 23,
"date": "2020-06-26 11:14:23",
"message": "Add %s something %s.",
"placeholder": {
"group_post": {
"id": 16,
"name": "Berlin",
"avatar": "source",
"post_id": 172,
"post_text": "asdasd..."
},
"group": {
"id": 16,
"name": "Bowling",
"avatar": "source",
"post_id": 172,
"post_text": "asdasd..."
}
}
},
{
"id": 246,
"type": 20,
"date": "2020-06-10 11:05:55",
"message": "You have rejected %s invitation to %s.",
"placeholder": {
"user": {
"id": 1283661,
"frozen": false,
"avatar": "source",
"private_data": false,
"login": "gut",
"online": 1
},
"group": {
"id": 24,
"name": "tomas",
"avatar": "source"
}
}
}
}
]
I have lists full of notifications but in case where user choose category I want to filter data and show only this values which user checked.
#Edit
Here is a custom "Checkbox"
<DropMenu
activator={({ isOpen, toggle, triggerRef, selectedItems }) => {
return (
<button type="button" ref={triggerRef} onClick={toggle}>
{selectedItems && selectedItems.length ? (
<Btn color="white">{selectedItems.map(val => `${val.content}, `)}</Btn>
) : (
<Btn color="white">None</Btn>
)}
</button>
);
}}
items={[
{
content: "value1",
value: 1,
},
{
content: "value2",
value: 2,
},
{
content: "value3",
value: 3,
},
{
content: "value4",
value: 4,
},
{
content: "value5",
value: 5,
},
{
content: "value6",
value: 6,
},
{
content: "value7",
value: 7,
},
]}
selected={select2}
onSelect={value => check2(value)}
/>
select2 is in hook's state and I want compare value from checkbox with types which api includes.
For example "value" 7 is equal "type" 23.
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
I have some multi-dimensional JSON data that contains different clothing items, each clothing item containing its own array of information.
I am trying to display this as such, using ReactJS:
{Product Name}
{size 1} has {quantity 1} in stock
{size 2} has {quantity 2} in stock
{size 3} has {quantity 3} in stock
My JSON looks like this:
{
"myShirt": [
{
"size": "Small",
"quantity": 0,
},
{
"size": "Medium",
"quantity": 0,
},
{
"size": "Large",
"quantity": 0,
},
],
"myShirt2": [
{
"size": "Small",
"quantity": 0,
},
{
"size": "Medium",
"quantity": 0,
},
{
"size": "Large",
"quantity": 0,
},
],
"myShirt3": [
{
"size": "Small",
"quantity": 0,
},
{
"size": "Medium",
"quantity": 0,
},
{
"size": "Large",
"quantity": 0,
},
]
}
So for example, in this case my desired output would be:
myShirt
Small has 0 in stock
Medium has 0 in stock
Large has 0 in stock
myShirt2
Small has 0 in stock
Medium has 0 in stock
Large has 0 in stock
myShirt3
Small has 0 in stock
Medium has 0 in stock
Large has 0 in stock
I have created a React component that includes this JSON data as part of its state. This component looks like this:
class Products extends React.Component {
constructor() {
super();
this.state = {
data: [
{
"myShirt": [
{
"size_text": "Small",
"quantity": 0,
},
{
"size_text": "Medium",
"quantity": 0,
},
{
"size_text": "Large",
"quantity": 0,
},
],
"myShirt2": [
{
"size_text": "Small",
"quantity": 3,
},
{
"size_text": "Medium",
"quantity": 0,
},
{
"size_text": "Large",
"quantity": 0,
},
],
"myShirt3": [
{
"size_text": "Small",
"quantity": 3,
},
{
"size_text": "Medium",
"quantity": 0,
},
{
"size_text": "Large",
"quantity": 0,
},
]
}]
}
}
render() {
return (
<div>
{
// HOW DO I DISPLAY MY OUTPUT HERE?
}
</div>
);
}
}
My approach to displaying my output was using .map. However, the bare code I used to do this wasn't successful. It looked like this:
render() {
return (
<div>
{
this.state.data.map((product, i) =>
<p>{product.map((productData, j) =>
<span>{productData.size_text}</span>
)
}</p>
)
}
</div>
);
}
This code doesn't attempt to display the entire output as I was just testing out the waters to see if I could get anything, at least a size to display. As you can tell, I'm pretty much stuck in the render function of the component. I don't know how I would access the product name, and moreover the product size name and quantity.
How would you go about solving this to get it to look like the desired output?
Thanks!
You can use Object.keys() to iterate through each key of state and then use array#map to iterate each array object.
class Products extends React.Component {
constructor() {
super();
this.state = { "myShirt": [ { "size_text": "Small", "quantity": 0 }, { "size_text": "Medium", "quantity": 0 }, { "size_text": "Large", "quantity": 0}, ], "myShirt2": [ { "size_text": "Small", "quantity": 3 }, { "size_text": "Medium", "quantity": 0}, { "size_text": "Large", "quantity": 0}, ], "myShirt3": [ { "size_text": "Small", "quantity": 3 }, { "size_text": "Medium", "quantity": 0}, { "size_text": "Large", "quantity": 0}, ] }
}
render() {
return (<div>{Object.keys(this.state).map(k => {
return <div>{k}<div>{
this.state[k].map(o => <div className={'left'}>{`${o.size_text} has ${o.quantity} in stock`}</div>)
}</div></div>
})}</div>)
}
}
ReactDOM.render(<Products />, document.getElementById('root'));
.left {
margin-left: 2em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='root'></div>
Well, I would've done it this way.
You can check console for logged values in desired format.
Now, I expect, you can add these values in your template yourself :)
Thanks
var stock = {
"myShirt": [
{
"size": "Small",
"quantity": 0,
},
{
"size": "Medium",
"quantity": 0,
},
{
"size": "Large",
"quantity": 0,
},
],
"myShirt2": [
{
"size": "Small",
"quantity": 0,
},
{
"size": "Medium",
"quantity": 0,
},
{
"size": "Large",
"quantity": 1,
},
],
"myShirt3": [
{
"size": "Small",
"quantity": 0,
},
{
"size": "Medium",
"quantity": 0,
},
{
"size": "Large",
"quantity": 0,
},
]
}
Object.keys(stock).map(e=>{
console.log(e+":");
stock[e].map(o=> console.log(o.size +" has "+o.quantity+" in stock"))
})
Thanks everyone for your comments!
To solve this I used a combination of two of the answers, and made my render function looks as such:
render() {
return (
<div id="product-container">{Object.keys(this.state.data).map(productId => {
return <div id="product-info">
<h2>{productId}</h2>
<div id="product-line-detail">{
this.state.data[productId].map(productDetail => <div className={'left'}>{`${productDetail.size_text} has ${productDetail.quantity} in stock`}</div>)
}
</div>
</div>
})}
</div>
)
}