Been racking my brains for a few days, and not getting any further forward.
I have a project using a MERN stack, and I'm trying to access a nested array from my database.
This is what my data structure looks like:
const Products = [
{
name: 'Air Zoom Pegasus 37',
brand: 'Nike',
category: 'running',
material: 'Textile & Synthetic Upper/Synthetic sole',
description: 'Hit a new PB in these mens Air Zoom Pegasus 37 trainers from Nike. In an Off Noir colourway with hits of Blue Fury and Bright Crimson, these runners have lightweight mesh upper for a breathable feel. They feature a secure lace up fastening and are sat on a soft foam midsole for long-lasting cushioning and maximum responsiveness. With Nikes Air Zoom unit at the forefront for a smooth ride, these trainers are finished with a grippy rubber tread and the iconic Swoosh logo to the sidewalls.',
price: 105,
sizes: [
{ size: '6', countInStock: 10 },
{ size: '7', countInStock: 10 },
{ size: '8', countInStock: 10 },
{ size: '9', countInStock: 10 },
{ size: '10', countInStock: 10 },
{ size: '11', countInStock: 10 },
{ size: '12', countInStock: 10 }
],
image1: '/images/nike_pegasus37_1.jpeg',
image2: '/images/nike_pegasus37_2.jpeg',
image3: '/images/nike_pegasus37_3.jpeg',
image4: '/images/nike_pegasus37_4.jpeg',
image5: '/images/nike_pegasus37_5.jpeg',
image6: '/images/nike_pegasus37_6.jpeg',
rating: 0,
numReviews: 0,
tags: 'nike, adidas, running, trainers, 5k, new, style',
},
]
I can't seem to access the nested objects in the 'Sizes' array. All the properties are returned in the state using Redux and I can see that the data payload returns all items from this BSON list in my Redux Devtools on Chrome.
I'm retrieving this data using Axios from a MongoDB collection, and using Redux to manage my state using dispatch and selector. Everything else works. I can fetch every other piece of information so I know it's not a back end problem, but I just can't seem to figure out how to map that array out.
Any help would be much appreciated.
Thanks,
Liam.
To map an array in react you can do it like this
Component start......
return {
<div>
{
// First map over your Products
// note the ? is there to prevent it from crashing if Products is not defined
Products?.map(product => {
return <>
<p>{product.name}</p>
//then map over this products sizes
<div>
{product?.sizes.map(size => {
return <p>{size.size} - {size.countInStock}</p>
})}
</div>
</>
})
}
</div>
}
Related
I am new to react js. I am trying to use the map function on an array that is stored in another file called products.js , when I console log the data it is showing by not showing in the screen. This is my code for the component:
import React from 'react'
import products from '../products'
import {Row,Col} from 'react-bootstrap'
const HomeScreen = () => {
console.log(products)
return (
<>
<h1>Latest Products</h1>
<Row>
{products.map(product => {
<h3 key={product._id}>{product.name}</h3>
})}
</Row>
</>
)
}
export default HomeScreen
This is the product.js code:
const products = [
{
_id: '1',
name: 'Airpods Wireless Bluetooth Headphones',
image: '/images/airpods.jpg',
description:
'Bluetooth technology lets you connect it with compatible devices wirelessly High-quality AAC audio offers immersive listening experience Built-in microphone allows you to take calls while working',
brand: 'Apple',
category: 'Electronics',
price: 89.99,
countInStock: 10,
rating: 4.5,
numReviews: 12,
},
{
_id: '2',
name: 'iPhone 11 Pro 256GB Memory',
image: '/images/phone.jpg',
description:
'Introducing the iPhone 11 Pro. A transformative triple-camera system that adds tons of capability without complexity. An unprecedented leap in battery life',
brand: 'Apple',
category: 'Electronics',
price: 599.99,
countInStock: 7,
rating: 4.0,
numReviews: 8,
},
{
_id: '3',
name: 'Cannon EOS 80D DSLR Camera',
image: '/images/camera.jpg',
description:
'Characterized by versatile imaging specs, the Canon EOS 80D further clarifies itself using a pair of robust focusing systems and an intuitive design',
brand: 'Cannon',
category: 'Electronics',
price: 929.99,
countInStock: 5,
rating: 3,
numReviews: 12,
},
{
_id: '4',
name: 'Sony Playstation 4 Pro White Version',
image: '/images/playstation.jpg',
description:
'The ultimate home entertainment center starts with PlayStation. Whether you are into gaming, HD movies, television, music',
brand: 'Sony',
category: 'Electronics',
price: 399.99,
countInStock: 11,
rating: 5,
numReviews: 12,
},
{
_id: '5',
name: 'Logitech G-Series Gaming Mouse',
image: '/images/mouse.jpg',
description:
'Get a better handle on your games with this Logitech LIGHTSYNC gaming mouse. The six programmable buttons allow customization for a smooth playing experience',
brand: 'Logitech',
category: 'Electronics',
price: 49.99,
countInStock: 7,
rating: 3.5,
numReviews: 10,
},
{
_id: '6',
name: 'Amazon Echo Dot 3rd Generation',
image: '/images/alexa.jpg',
description:
'Meet Echo Dot - Our most popular smart speaker with a fabric design. It is our most compact smart speaker that fits perfectly into small space',
brand: 'Amazon',
category: 'Electronics',
price: 29.99,
countInStock: 0,
rating: 4,
numReviews: 12,
},
]
export default products
And this is my App.js code :
import React from 'react'
import {Container} from 'react-bootstrap'
import Header from './components/Header'
import Footer from './components/Footer'
import HomeScreen from './screens/HomeScreen'
const App=()=> {
return (
<>
<Header />
<main>
<Container className='py-3'>
<HomeScreen/>
</Container>
</main>
<Footer/>
</>
);
}
export default App;
Why is this happening? I have tried looking up some solutions but failed. Thank you for helping
Add a return statement in the map function.
{products.map((product) => {
return <h3 key={product._id}>{product.name}</h3>;
})}
I think the problem is that you need to add a return statement before the h3:
<Row>
{products.map(product => {
return <h3 key={product._id}>{product.name}</h3>
})}
</Row>
If you want to do it this way without using 'return', there are 2 options:
Option 1: Remove the curly braces
<Row>
{products.map(product => return <h3 key={product._id}>{product.name}</h3>)}
</Row>
Option 2: Use () instead of the curly braces (Most especially when you are gonna add more elements later)
<Row>
{products.map(product => (
<h3 key={product._id}>{product.name}</h3>
<...other html elements>
))}
</Row>
This question already has answers here:
MongoDB: How to update multiple documents with a single command?
(13 answers)
Closed 3 years ago.
I looked at other questions and I feel mine was different enough to ask.
I am sending a (potentially) large amount of information back to my backend, here is an example data set:
[ { orders: [Array],
_id: '5c919285bde87b1fc32b7553',
name: 'Test',
date: '2019-03-19',
customerName: 'Amego',
customerPhone: '9991112222',
customerStreet: 'Lost Ave',
customerCity: 'WestZone',
driver: 'CoolCat',
driverReq: false, // this is always false when it is ready to print
isPrinted: false, // < this is important
deliveryCost: '3',
total: '38.48',
taxTotal: '5.00',
finalTotal: '43.48',
__v: 0 },
{ orders: [Array],
_id: '5c919233bde87b1fc32b7552',
name: 'Test',
date: '2019-03-19',
customerName: 'Foo',
customerPhone: '9991112222',
customerStreet: 'Found Ave',
customerCity: 'EastZone',
driver: 'ChillDog',
driverReq: false,// this is always false when it is ready to print
isPrinted: false, // < this is important
deliveryCost: '3',
total: '9.99',
taxTotal: '1.30',
finalTotal: '11.29',
__v: 0 },
{ orders: [Array],
_id: '5c91903b6e0b7f1f4afc5c43',
name: 'Test',
date: '2019-03-19',
customerName: 'Boobert',
customerPhone: '9991112222',
customerStreet: 'Narnia',
customerCity: 'SouthSzone',
driver: 'SadSeal',
driverReq: false,// this is always false when it is ready to print
isPrinted: false, // < this is important
deliveryCost: '3',
total: '41.78',
taxTotal: '5.43',
finalTotal: '47.21',
__v: 0 } ] }
My front end can find all the orders that include isPrinted:false, I then allow the end user to 'print' all the orders that are prepared, in which, I need to change isPrinted into true, that way when I pull up a next batch I won't have reprints.
I was looking at db.test.updateMany({foo: "bar"}, {$set: {isPrinted: true}}), and I currently allow each order to set a new driver, which I update by:
Order.update({
_id: mongoose.Types.ObjectId(req.body.id)
},
{
$set: {
driver:req.body.driver, driverReq:false
}
which is pretty straight forward, as only 1 order comes back at a time.
I have considered my front end doing a foreach and posting each order individually, then updating the isPrinted individually but that seems quite inefficient. Is there a elegant solutions within mongo for this?
I'm not sure how I would user updateMany considering each _id is unique, unless I grab all the order's who are both driverReq:false and isPrinted:false (because that is the case where they are ready to print.
I found a solution, that was in fact using UpdateMany.
Order.updateMany({
isPrinted: false, driverReq:false
},
{
$set: {
isPrinted: true
}
consider there this special case where both are false when it needs to be changed too true. But I do wonder if there is a way to iterate over multiple document id's with ease.
Not quite sure if that title was the best I could do.
I'm a pretty new to js and keep running into problems ... I hope some of you have the time to give me a pointer or two on this scenario.
I have several objects that looks pretty much like this - except from the fact that there are 28 instances of every "room" type. I need to split this object into multiple objects - one for each "room" type. In some of my objects there are only one room type - whilst in others there are 3 or 4.
[ { id: 1
created: 2018-12-29T13:18:05.788Z,
room: 'Double Room'
type: 'Standard'
price: 500
},
{ id: 29
created: 2018-12-29T13:18:05.788Z,
room: 'Twin Room'
type: 'Standard'
price: 500
},
{ id: 58
created: 2018-12-29T13:18:05.788Z,
room: 'Family Room'
type: 'Standard'
price: 900
},
]
Oh, and it's important that the instances don't "loose" their order in the array - since it's date related and need to be presentet in an ascending order. And vanilla js only.
Is array.map() the function I'm looking for to solve this problem? Is it posible to do this without iteration?
My final goal is to create some kind of generic function that can sort this out for all my objects.
And guys: happy hollidays!
You could take an object as hash table for the wanted groups. Then iterate the objects and assign the object to the group. If the group does not exist, create a new group with an array.
function groupBy(array, key) {
var groups = Object.create(null);
array.forEach(o => (groups[o[key]] = groups[o[key]] || []).push(o));
return groups;
}
var data = [{ id: 1, created: '2018-12-29T13:18:05.788Z', room: 'Double Room', type: 'Standard', price: 500 }, { id: 29, created: '2018-12-29T13:18:05.788Z', room: 'Twin Room', type: 'Standard', price: 500 }, { id: 58, created: '2018-12-29T13:18:05.788Z', room: 'Family Room', type: 'Standard', price: 900 }],
groupedByRoom = groupBy(data, 'room');
console.log(groupedByRoom);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I can currently scrape Javascript data from a post request I sent using requests then Soup. But I only want to scrape the product plu, sku, description and brand. I am struggling to find a way in which I can just print the data I need rather then the whole script. This is the text that is printed after I extract the script using soup. I will be scraping more than one product from multiple post requests, so the chunk idea is not really suitable.
<script type="text/javascript">
var dataObject = {
platform: 'desktop',
pageType: 'basket',
orderID: '',
pageName: 'Basket',
orderTotal: '92.99',
orderCurrency: 'GBP',
currency: 'GBP',
custEmail: '',
custId: '',
items: [
{
plu: '282013',
sku: '653460',
category: 'Footwear',
description: 'Mayfly Lite Pinnacle Women's',
colour: '',
brand: 'Nike',
unitPrice: '90',
quantity: '1',
totalPrice: '90',
sale: 'false'
} ]
};
As you can see it is far too much information.
How about this:
You assign the captured text to a new multiline string variable called "chunk"
Make a list of keys you are looking for
Loop over each line to check if the line has a term that you want, and then print out that term:
chunk = '''
<script type="text/javascript">
var dataObject = {
.........blah blah.......
plu: '282013',
sku: '653460',
category: 'Footwear',
description: 'Mayfly Lite Pinnacle Women's',
colour: '',
brand: 'Nike',
..... blah .......
};'''
keys = ['plu', 'sku', 'description', 'brand']
for line in chunk.splitlines():
if line.split(':')[0].strip() in keys:
print line.strip()
Result:
plu: '282013',
sku: '653460',
description: 'Mayfly Lite Pinnacle Women's',
brand: 'Nike',
You could obviously clean up the result using similar applications of split, strip, replace, etc.
I'm building a web scraper in nodeJS that uses request and cheerio to parse the DOM. While I am using node, I believe this is more of a general javascript question.
tl;dr - creating ~60,000 - 100,000 objects, uses up all my computer's RAM, get an out of memory error in node.
Here's how the scraper works. It's loops within loops, I've never designed anything this complex before so there might be way better ways to do this.
Loop 1: Creates 10 objects in array called 'sitesArr'. Each object represents one website to scrape.
var sitesArr = [
{
name: 'store name',
baseURL: 'www.basedomain.com',
categoryFunct: '(function(){ // do stuff })();',
gender: 'mens',
currency: 'USD',
title_selector: 'h1',
description_selector: 'p.description'
},
// ... x10
]
Loop 2: Loops through 'sitesArr'. For each site it goes to the homepage via 'request' and gets a list of category links, usually 30-70 URLs. Appends these URLs to the current 'sitesArr' object to which they belong, in an array property whose name is 'categories'.
var sitesArr = [
{
name: 'store name',
baseURL: 'www.basedomain.com',
categoryFunct: '(function(){ // do stuff })();',
gender: 'mens',
currency: 'USD',
title_selector: 'h1',
description_selector: 'p.description',
categories: [
{
name: 'shoes',
url: 'www.basedomain.com/shoes'
},{
name: 'socks',
url: 'www.basedomain.com/socks'
} // x 50
]
},
// ... x10
]
Loop 3: Loops through each 'category'. For each URL it gets a list of products links and puts them in an array. Usually ~300-1000 products per category
var sitesArr = [
{
name: 'store name',
baseURL: 'www.basedomain.com',
categoryFunct: '(function(){ // do stuff })();',
gender: 'mens',
currency: 'USD',
title_selector: 'h1',
description_selector: 'p.description',
categories: [
{
name: 'shoes',
url: 'www.basedomain.com/shoes',
products: [
'www.basedomain.com/shoes/product1.html',
'www.basedomain.com/shoes/product2.html',
'www.basedomain.com/shoes/product3.html',
// x 300
]
},// x 50
]
},
// ... x10
]
Loop 4: Loops through each of the 'products' array, goes to each URL and creates an object for each.
var product = {
infoLink: "www.basedomain.com/shoes/product1.html",
description: "This is a description for the object",
title: "Product 1",
Category: "Shoes",
imgs: ['http://foo.com/img.jpg','http://foo.com/img2.jpg','http://foo.com/img3.jpg'],
price: 60,
currency: 'USD'
}
Then, for each product object I'm shipping them off to a MongoDB function which does an upsert into my database
THE ISSUE
This all worked just fine, until the process got large. I'm creating about 60,000 product objects every time this script runs, and after a little while all of my computer's RAM is being used up. What's more, after getting about halfway through my process I get the following error in Node:
FATAL ERROR: CALL_AND_RETRY_2 Allocation failed - process out of memory
I'm very much of the mind that this is a code design issue. Should I be "deleting" the objects once I'm done with them? What's the best way to tackle this?