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)
Related
So I can call the variable "teams" and see the data fine but I can't get the values from it in my {#each} block. I know its not part of the "fixtures" variable I'm iterating through and tbh that's probably the issue.
Does anyone know how I can get the actual values within "teams" instead of getting 'undefined' or a better way of fetching multiple arrays within themselves? (ill put the example at the bottom)
my +page.svelte
<script>
export let data;
const { fixtures } = data;
const teams = fixtures.flatMap(fixtures => fixtures.participants)
console.log(teams)
</script>
<div class="flex flex-col absolute top-[0] right-0 w-[85vw] p-6">
<div class="">
{#each fixtures as fixture}
<p>{fixture.name}</p>
<div class="">{fixture.home_score}{fixture.away_score}</div>
<p>{teams.short_code}</p>
{/each}
</div>
</div>
+page.server.js
export const load = async () => {
const fetchList= async () => {
const url = `https://api.sportmonks.com/v3/football/schedules/seasons/19734?api_token=${process.env.API_KEY}`;
const res = await fetch(url);
const data = await res.json()
return data.data.flatMap(data => data.rounds.map(rounds => rounds.fixtures)).flat()
}
return {
fixtures: fetchList(),
}
}
The API
{
"data": [
{
"id": 77457864,
"sport_id": 1,
"league_id": 8,
"season_id": 19734,
"type_id": 223,
"name": "Regular Season",
"sort_order": 1,
"finished": false,
"is_current": true,
"starting_at": "2022-08-05",
"ending_at": "2023-05-28",
"rounds": [
{
"id": 274668,
"sport_id": 1,
"league_id": 8,
"season_id": 19734,
"stage_id": 77457864,
"name": "1",
"finished": true,
"is_current": false,
"starting_at": "2022-08-05",
"ending_at": "2022-08-07",
"fixtures": [
{
"id": 18535049,
"sport_id": 1,
"league_id": 8,
"season_id": 19734,
"stage_id": 77457864,
"group_id": null,
"aggregate_id": null,
"round_id": 274668,
"state_id": 5,
"venue_id": 206,
"name": "Manchester United vs Brighton & Hove Albion",
"home_score": 1,
"away_score": 2,
"starting_at": "2022-08-07 13:00:00",
"result_info": "Brighton & Hove Albion won after full-time.",
"leg": "1/1",
"details": null,
"length": 90,
"placeholder": false,
"last_processed_at": "2022-12-05 09:15:37",
"starting_at_timestamp": 1659877200,
"participants": [
{
"id": 14,
"sport_id": 1,
"country_id": 462,
"venue_id": 206,
"gender": "male",
"name": "Manchester United",
"short_code": "MUN",
"image_path": "https://cdn.sportmonks.com/images/soccer/teams/14/14.png",
"founded": 1878,
"type": "domestic",
"placeholder": false,
"last_played_at": "2022-12-10 17:00:00",
"meta": {
"location": "home"
}
},
{
"id": 78,
"sport_id": 1,
"country_id": 462,
"venue_id": 480,
"gender": "male",
"name": "Brighton & Hove Albion",
"short_code": "BRH",
"image_path": "https://cdn.sportmonks.com/images/soccer/teams/14/78.png",
"founded": 1901,
"type": "domestic",
"placeholder": false,
"last_played_at": "2022-12-08 13:00:00",
"meta": {
"location": "away"
}
}
]
},
There's a "dirty" way to do it with {#key}
I am working on a list app, and I am having issues with the components not updating correctly. I pull the users list from a JSON file and save it in a state. I am using context to pass that state and other information around to my different compoents. The smallest component is the user items broken out into a list which is editable. It is here with the list of items that I am having issues with.
For example, I have two different JSON files:
[{"userId": 81944,
"listId": 1,
"title": "testa",
"items": [
{
"listItemId": 0,
"product": "walnuts",
"quantity": 1,
"category": "Bakery",
"unit": "Each",
"cart": false
},
{
"listItemId": 1,
"product": "syrup",
"quantity": 1,
"category": "Beverages",
"unit": "Each",
"cart": true
},
{
"listItemId": 2,
"product": "cinnamon",
"quantity": 6,
"category": "Bakery",
"unit": "Each",
"cart": false
},
{
"listItemId": 3,
"product": "gabonzo beans",
"quantity": 1,
"category": "Canned Goods",
"unit": "Each",
"cart": true
},
{
"listItemId": 4,
"product": "diced tomatos",
"quantity": 7,
"category": "Produce",
"unit": "Each",
"cart": false
},
{
"listItemId": 5,
"product": "milk",
"quantity": 1,
"category": "Dairy",
"unit": "Oz",
"cart": false
},
{
"listItemId": 6,
"product": "salmon",
"quantity": 3,
"category": "Meat",
"unit": "Lb",
"cart": false
}]},{
"userId": 78863,
"listId": 4,
"title": "testd",
"items": [
{
"listItemId": 0,
"product": "half and half",
"quantity": 1,
"category": "Dairy",
"unit": "Each",
"cart": false
},
{
"listItemId": 1,
"product": "Blue Cheese",
"quantity": 1,
"category": "Dairy",
"unit": "Each",
"cart": false
},
{
"listItemId": 2,
"product": "Garlic",
"quantity": 1,
"category": "Produce",
"unit": "Each",
"cart": false
},
{
"listItemId": 3,
"product": "Chestnuts",
"quantity": 1,
"category": "Other",
"unit": "Each",
"cart": false
},
{
"listItemId": 4,
"product": "Balsamic Vinegar",
"quantity": 1,
"category": "Other",
"unit": "Each",
"cart": false
},
{
"listItemId": 5,
"product": "Onions",
"quantity": 1,
"category": "Produce",
"unit": "Each",
"cart": false
},
{
"listItemId": 6,
"product": "Flax Seed",
"quantity": 1,
"category": "others",
"unit": "Each",
"cart": false
},
{
"listItemId": 7,
"product": "Plantains",
"quantity": 1,
"category": "Produce",
"unit": "Each",
"cart": false
}]}]
In my app I have a dialog box that allows me to switch between my lists. I then take list and pass it a custom component to be drawn on the screen.
import React, {useState,useEffect} from 'react';
const Card=(props)=>{
//console.log('prop');
const [cart, setCart] = useState(props.cart);
const [Product, setProduct] = useState(props.item);
const [Quantity, setQuantity] = useState(props.units);
// useEffect(()=>{
// setProduct(props.item)
// setQuantity(props.units)
// setCart(props.cart);
// },[])
console.log(props)
return (
<li key={props.value}>
<div>
<input type="checkbox" checked={cart} onChange={(e)=>{props.cartChange(e.target)}}/>
</div>
<div>
<input id={'product '+props.value} className='update'
type='text' value={Product}
onChange={(e)=>setProduct(e.target.value)}
/>
<br/>
<input id='quantityValue' className='update'
type='number' value={Quantity}
onChange={(e)=>setQuantity(e.target.value)}
/>
<span id='quantityType' className='update'>{props.unitType}</span>
</div>
<div>
<button id='save-button' type='button'
onClick={(e)=>{props.change(Product,Quantity,props.value)}}>✓ save</button>
<button id='delete-button' type='button'>✗ delete</button>
</div>
</li>
)
}
export default Card;
This is the code that calls the custom components. You will see that I am calling it from a array.map() those arrays are fine, and have the correct information in them.
import React, {useContext,useEffect} from 'react';
import {DataContext} from '../../../context/test/DataContext'
import Card from './ItemCard';
const update=(x)=>{
console.log(x)
}
const List = () =>{
const {listId} = useContext(DataContext);
const {userItemList} = useContext(DataContext);
const {GetItemList} = useContext(DataContext);
const {ListSplit} = useContext(DataContext);
const {foundList} = useContext(DataContext);
const {findList} = useContext(DataContext);
const {Updater} = useContext(DataContext);
const {cartUpdater} = useContext(DataContext);
useEffect(()=>{
GetItemList();
},[listId])
useEffect(()=>{
ListSplit();
},[userItemList])
// console.log(findList);
// console.log(foundList);
return(
<div>
<p>To find:</p>
<ul>
{findList.map((item,index)=><Card key={item.listItemId} index={index}
value={item.listItemId} cart={item.cart} item={item.product}
units={item.quantity} unitType={item.unit}
cartChange={cartUpdater} change={Updater} />)}
</ul>
<p>Found:</p>
<ul>
{foundList.map((item,index)=><Card key={item.listItemId} index={index}
value={item.listItemId} cart={item.cart} item={item.product}
units={item.quantity} unitType={item.unit}
cartChange={cartUpdater} change={Updater} />)}
</ul>
</div>
)
}
export default List;
Each time I switch this, the props that I console log out change correctly. Also, if I look at my compoents in dev tools (chrome) I see that the states should be correct, however what I see on the screen is not correct. For example the second item which is cinnamon, if I switch to the second list should be Blue Cheese. The prop changes, as does the state, but what I see on the screen is still cinnamon.
I know that I probably didnt explain it that clearly, but below is a screen shot of what I am talking about.
You were close with the commented out code. Since you are setting your props to state (which is a bad idea and I will discuss at the bottom), your useState only sets the state initially. You want to watch these props and update when they do.
useEffect(() => {
setProduct(props.item)
setQuantity(props.units)
setCart(props.cart);
}, [props.item, props.units, props.cart]);
The items in the array are what useEffect watches to know if it should fire.
As a side note - assigning props to state is a bad idea and you've seen why - they don't automatically update. You should hoist up where these props are set to the parent and you can pass them down as props and use them directly. You can pass down the setters as props as well, which can update the parent.
This article, while referencing class based React component may provide more information if you'd care to read up on it.
const { useState } = React;
const initialItems = [
{
listItemId: 1,
product: 'syrup',
quantity: 1,
category: 'Beverages',
unit: 'Each',
cart: true,
},
{
listItemId: 2,
product: 'cinnamon',
quantity: 6,
category: 'Bakery',
unit: 'Each',
cart: false,
},
{
listItemId: 3,
product: 'garbanzo beans',
quantity: 1,
category: 'Canned Goods',
unit: 'Each',
cart: true,
},
];
const Parent = () => {
const [items, setItems] = useState(initialItems);
const updateProduct = listItemId => (e) => {
setItems(items.map((item) => {
if (item.listItemId === listItemId) {
return { ...item, product: e.target.value };
}
return item;
}));
};
const updateQuantity = listItemId => (e) => {
setItems(items.map((item) => {
if (item.listItemId === listItemId) {
return { ...item, quantity: e.target.value };
}
return item;
}));
};
return (
<div>
<div style={{ width: "50%" }}>
All Items - (this state lives inside the parent component)
</div>
<div>
{items.map(item => (
<div>
<div>
Product - {item.product}
</div>
<div>
Quantity - {item.quantity}
</div>
</div>
))}
</div>
<div style={{ width: "50%" }}>
{items.map(item => (
<Child item={item} updateQuantity={updateQuantity} updateProduct={updateProduct} />
))}
</div>
</div>
);
};
const Child = ({ item, updateQuantity, updateProduct }) => {
return (
<div>
<div>
<span>
Product -
</span>
<span>
<input value={item.product} onChange={updateProduct(item.listItemId)} />
</span>
</div>
<div>
<span>
Quantity -
</span>
<span>
<input value={item.quantity} onChange={updateQuantity(item.listItemId)} />
</span>
</div>
</div>
);
};
ReactDOM.render(
<Parent />,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>
A little example above. The parent component holds the state of the items and maps over each to create a child component. This example is a little rough around the edges. You could do something like adding data-id and name to each input to simplify the updating functions, or use useReducer to hoist that logic a bit, but I think it gets you going in the right direction.
I currently have an array of array of objects and wanting to print in a specific format based on each array inside of the master array. Each array basically represents a full order and the objects inside are the order items.
Array [
Array [
Object {
"name": "Angela Braun",
"order_id": 1,
"price": 39.51,
"product_id": 2,
"quantity": 1,
"size": "S",
"status": "placed",
"updated_at": "2019-11-16 13:36:03",
"user_id": 2,
},
],
Array [
Object {
"name": "Angela Braun",
"order_id": 2,
"price": 39.51,
"product_id": 2,
"quantity": 1,
"size": "S",
"status": "placed",
"updated_at": "2019-11-16 13:36:03",
"user_id": 2,
},
Object {
"name": "Fred Schmidt",
"order_id": 2,
"price": 12.17,
"product_id": 1,
"quantity": 1,
"size": "S",
"status": "placed",
"updated_at": "2019-11-16 13:36:03",
"user_id": 2,
},
Object {
"name": "Margie Legros",
"order_id": 2,
"price": 9.48,
"product_id": 4,
"quantity": 1,
"size": "S",
"status": "placed",
"updated_at": "2019-11-16 13:36:03",
"user_id": 2,
},
],
]
The format I want is
Order 1:
Items
Order 2:
Items
Order 3:
Items
etc.
What I've tried:
{orders ?
orders.map((order, index) => (
<Text>Order {order[index].order_id}</Text>
order.map(o => (
<Text>Name: {o.name} Quantity: {o.quantity}</Text>
))
))
: null}
The error I get is:
')' expected.ts(1005)
Which is referring to the map. How would I achieve this layout?
I think the following should straighten you out. You had the following issues: 1) you just need to pull the order_id from the first element of the orders array, 2) You need to have a React.Fragment parent for the nested map, and 3) You needed to add {} around your nested map.
{orders &&
orders.map(order => (
<React.Fragment>
<Text>Order {order[0].order_id}</Text>
{order.map(o => (
<Text>Name: {o.name} Quantity: {o.quantity}</Text>
))}
</React.Fragment>
))
}
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'm trying to accessing a json child object which is not in an array. i've tried accessing it with my below script but its not working. i want to be able to access the menuCategory Object
JSON
[
{
"id": 67,
"name": "Wednesday Menu",
"serveDate": "2019-06-12 00:00:00",
"expiryDate": "2019-06-12 16:11:00",
"status": "APPROVED",
"isEnabled": true,
"meals": [
{
"id": 45,
"name": "Waakye, Gari and Wele",
"description": "A very well designed food for all kids",
"image": "",
"mealType": "LUNCH",
"unitPrice": 30,
"status": "ENABLED"
},
{
"id": 46,
"name": "Gari and Beans",
"description": "A very well designed food for all kidsss",
"image": "",
"mealType": "LUNCH",
"unitPrice": 12,
"status": "ENABLED"
}
],
"menuCategory": {
"id": 2,
"name": "hello"
}
}
]
JAVASCRIPT
callEditMenu(parent, content) {
this.modalService.open(content);
this.editMenuCategoryId = parent.menuCategory.id;
}
May be like
const parent = [{"id":67,"name":"Wednesday Menu","serveDate":"2019-06-12 00:00:00","expiryDate":"2019-06-12 16:11:00","status":"APPROVED","isEnabled":true,"meals":[{"id":45,"name":"Waakye, Gari and Wele","description":"A very well designed food for all kids","image":"","mealType":"LUNCH","unitPrice":30,"status":"ENABLED"},{"id":46,"name":"Gari and Beans","description":"A very well designed food for all kidsss","image":"","mealType":"LUNCH","unitPrice":12,"status":"ENABLED"}],"menuCategory":{"id":2,"name":"hello"}}]
console.log(parent[0].menuCategory.id);
If the parent argument in the callEditMenu function is referring to the JSON you included then try parent[0].menuCategory.id
let arr = [{"id":67,"name":"Wednesday Menu","serveDate":"2019-06-12 00:00:00","expiryDate":"2019-06-12 16:11:00","status":"APPROVED","isEnabled":true,"meals":[{"id":45,"name":"Waakye, Gari and Wele","description":"A very well designed food for all kids","image":"","mealType":"LUNCH","unitPrice":30,"status":"ENABLED"},{"id":46,"name":"Gari and Beans","description":"A very well designed food for all kidsss","image":"","mealType":"LUNCH","unitPrice":12,"status":"ENABLED"}],"menuCategory":{"id":2,"name":"hello"}}]
for (let item of arr) {
if (item.hasOwnProperty("menuCategory")) {
console.log(item["menuCategory"]);
}
};
let res = arr.filter((item) => item && item.menuCategory);
console.log(res[0].menuCategory);
In case you need to find it dynamically. Above are two different ways
Considering there would be multiple items in your array of objects, you can iterate through each object to get the menuCategory name as
let obj = [
{
"id": 67,
"name": "Wednesday Menu",
"serveDate": "2019-06-12 00:00:00",
"expiryDate": "2019-06-12 16:11:00",
"status": "APPROVED",
"isEnabled": true,
"meals": [
{
"id": 45,
"name": "Waakye, Gari and Wele",
"description": "A very well designed food for all kids",
"image": "",
"mealType": "LUNCH",
"unitPrice": 30,
"status": "ENABLED"
},
{
"id": 46,
"name": "Gari and Beans",
"description": "A very well designed food for all kidsss",
"image": "",
"mealType": "LUNCH",
"unitPrice": 12,
"status": "ENABLED"
}
],
"menuCategory": {
"id": 2,
"name": "hello"
}
}
];
obj.forEach(elem => {
console.log(elem.menuCategory.name);
});