In a small ecommerce project (sourcing data from WooCommerce) in ReactJs i have a variable product
Besides all the product data i got two array object representing the product variations, one contains all the available attribute and options:
nodes: Array(3)
0:
id: "d2VpZ2h0OjMxOldlaWdodA=="
name: "Weight"
options: Array(2)
0: "250gr"
1: "500gr"
position: 0
variation: true
visible: true
1:
id: "cm9hc3Q6MzE6Um9hc3Q="
name: "Roast"
options: Array(3)
0: "Light"
1: "Medium"
2: "Dark"
position: 1
variation: true
visible: true
2:
id: "cGFja2FnaW5nOjMxOlBhY2thZ2luZw=="
name: "Packaging"
options: Array(2)
0: "Card"
1: "Tin"
position: 2
variation: true
visible: true
I save this one in a state and use it to build the select (3 select in this case)
then i have an array of object which contans all the available combinations, with price, id and so on:
nodes: Array(5)
0:
attributes:
nodes: Array(3)
0: {id: "NDB8fHdlaWdodHx8MjUwZ3I=", name: "weight", value: "250gr"}
1: {id: "NDB8fHJvYXN0fHxNZWRpdW0=", name: "roast", value: "Medium"}
2: {id: "NDB8fHBhY2thZ2luZ3x8Q2FyZA==", name: "packaging", value: "Card"}
id: "cHJvZHVjdF92YXJpYXRpb246NDA="
price: "€7,00"
variationId: 40
1:
attributes:
nodes: Array(3)
0: {id: "Mzh8fHdlaWdodHx8NTAwZ3I=", name: "weight", value: "500gr"}
1: {id: "Mzh8fHJvYXN0fHxEYXJr", name: "roast", value: "Dark"}
2: {id: "Mzh8fHBhY2thZ2luZ3x8VGlu", name: "packaging", value: "Tin"}
length: 3
id: "cHJvZHVjdF92YXJpYXRpb246Mzg="
price: "€12,00"
variationId: 38
2:
attributes:
nodes: Array(3)
0: {id: "Mzd8fHdlaWdodHx8NTAwZ3I=", name: "weight", value: "500gr"}
1: {id: "Mzd8fHJvYXN0fHxNZWRpdW0=", name: "roast", value: "Medium"}
2: {id: "Mzd8fHBhY2thZ2luZ3x8VGlu", name: "packaging", value: "Tin"}
length: 3
id: "cHJvZHVjdF92YXJpYXRpb246Mzc="
price: "€12,00"
variationId: 37
3:
attributes:
nodes: Array(3)
0: {id: "MzZ8fHdlaWdodHx8NTAwZ3I=", name: "weight", value: "500gr"}
1: {id: "MzZ8fHJvYXN0fHxMaWdodA==", name: "roast", value: "Light"}
2: {id: "MzZ8fHBhY2thZ2luZ3x8VGlu", name: "packaging", value: "Tin"}
id: "cHJvZHVjdF92YXJpYXRpb246MzY="
price: "€12,00"
variationId: 36
4:
attributes:
nodes: Array(3)
0: {id: "MzR8fHdlaWdodHx8MjUwZ3I=", name: "weight", value: "250gr"}
1: {id: "MzR8fHJvYXN0fHxMaWdodA==", name: "roast", value: "Light"}
2: {id: "MzR8fHBhY2thZ2luZ3x8Q2FyZA==", name: "packaging", value: "Card"}
length: 3
id: "cHJvZHVjdF92YXJpYXRpb246MzQ="
price: "€7,00"
variationId: 34
Basically, when i select something on any select, the other select shoould filter based on the avaialble variations: if i select 250gr as weight, the Dark Roast and the Tin Packaging sould be removed from their select since they arent combinable with 250gr; if i switch back to 500gr (or to "no option selected") they should reappear in the same place as they were before.
on the basic WooCommerce product page it already works this way (you can check its behaviour here: https://shop.popland.it/prodotto/coffee-bean/) but replicating it in ReactJs its harder than i was thinking.
At the moment im stuck on loop that generate the select with an empty onChange handler:
const [attr, setAttr] = useState(product.attributes);
<div>
{attr.nodes.map((attribute, l) => {
return (
<div key={l}>
<span>{attribute.name}</span>
<select
id={attribute.name}
onChange={handleChange}
data-attribute_name={`attribute_${attribute.name}`}
>
<option>Select option</option>
{attribute.options.map((option, o) => {
return (
<option key={o} value={option}>
{option}
</option>
);
})}
</select>
</div>
);
})}
</div>
Any suggetion/help on how to go on from here?
here is my solution.
/src/hooks.js
import { useState } from "react";
import { filterVariations, formatVariations } from "./helpers";
export function useVariations(product) {
const [state, setState] = useState({});
const filteredVariations = filterVariations(
product?.variations?.nodes,
state,
);
const formatedVariations = formatVariations(
filteredVariations,
product?.variations?.nodes,
);
return [formatedVariations, state, setState];
}
/src/helpers.js
export function filterVariations(variations, state) {
if (Object.keys(state).length === 0) {
return variations;
}
return Object.keys(state)?.reduce((accStateVars, currStateVar) => {
return accStateVars.reduce((accVars, currVar) => {
const filteredAttrsByName = currVar?.attributes?.nodes?.filter(
(attr) => currStateVar === attr?.name,
);
const withSelected = currVar?.attributes?.nodes?.findIndex(
(attr) => attr?.attributeId === state?.[currStateVar]?.value,
);
return [
...accVars,
{
attributes: {
nodes:
withSelected >= 0
? currVar?.attributes?.nodes
: filteredAttrsByName,
},
},
];
}, []);
}, variations);
}
export function formatVariations(filteredVariations, variations) {
const defaultSelects = variations?.reduce(
(accVars, currVar) => ({
...accVars,
...currVar?.attributes?.nodes?.reduce(
(accAttrs, currAttr) => ({ ...accAttrs, [currAttr.name]: {} }),
{},
),
}),
{},
);
return filteredVariations.reduce((accVars, currVar) => {
const filteredAttrs = currVar?.attributes?.nodes?.reduce(
(accAttrs, currAttr) => {
const exists =
0 <=
accVars[currAttr.name]?.options?.findIndex(
(option) => option.value === currAttr.attributeId,
);
return {
...accAttrs,
[currAttr.name]: {
placeholder: currAttr.label,
options: exists
? accVars[currAttr.name]?.options || []
: [
...(accVars[currAttr.name]?.options || []),
{ label: currAttr.value, value: currAttr.attributeId },
],
},
};
},
{},
);
return { ...accVars, ...filteredAttrs };
}, defaultSelects);
}
/src/App.js
import "./styles.css";
import Select from "react-select";
import { useVariations } from "./hooks";
const product = {
variations: {
nodes: [
{
attributes: {
nodes: [
{
name: "pa_size",
attributeId: 254,
id: "NTY5MHx8cGFfc2l6ZXx8MTItc3BlYWtlcg==",
label: "Size",
value: '12" Speaker',
},
{
name: "pa_color",
attributeId: 304,
id: "NTY5MHx8cGFfY29sb3J8fGdyYXBoaXRl",
label: "Color",
value: "Graphite",
},
{
name: "pa_flavor",
attributeId: 320,
id: "NTY5MHx8cGFfZmxhdm9yfHxnb2xk",
label: "Flavor",
value: "Gold",
},
{
name: "pa_pallet",
attributeId: 336,
id: "NTY5MHx8cGFfcGFsbGV0fHxncmVlbg==",
label: "Pallet",
value: "Green",
},
],
},
},
{
attributes: {
nodes: [
{
name: "pa_size",
attributeId: 255,
id: "NTY4Nnx8cGFfc2l6ZXx8MTAtc3BlYWtlcg==",
label: "Size",
value: '10" Speaker',
},
{
name: "pa_color",
attributeId: 67,
id: "NTY4Nnx8cGFfY29sb3J8fGJlaWdl",
label: "Color",
value: "Beige",
},
{
name: "pa_flavor",
attributeId: 320,
id: "NTY4Nnx8cGFfZmxhdm9yfHxnb2xk",
label: "Flavor",
value: "Gold",
},
{
name: "pa_pallet",
attributeId: 337,
id: "NTY4Nnx8cGFfcGFsbGV0fHxwZWFjaA==",
label: "Pallet",
value: "Peach",
},
],
},
},
{
attributes: {
nodes: [
{
name: "pa_size",
attributeId: 255,
id: "NTY4N3x8cGFfc2l6ZXx8MTAtc3BlYWtlcg==",
label: "Size",
value: '10" Speaker',
},
{
name: "pa_color",
attributeId: 439,
id: "NTY4N3x8cGFfY29sb3J8fGZhdGFsLWFwcGxl",
label: "Color",
value: "Fatal Apple",
},
{
name: "pa_flavor",
attributeId: 319,
id: "NTY4N3x8cGFfZmxhdm9yfHx2YW5pbGxh",
label: "Flavor",
value: "Vanilla",
},
{
name: "pa_pallet",
attributeId: 336,
id: "NTY4N3x8cGFfcGFsbGV0fHxncmVlbg==",
label: "Pallet",
value: "Green",
},
],
},
},
{
attributes: {
nodes: [
{
name: "pa_size",
attributeId: 254,
id: "NTY4OHx8cGFfc2l6ZXx8MTItc3BlYWtlcg==",
label: "Size",
value: '12" Speaker',
},
{
name: "pa_color",
attributeId: 67,
id: "NTY4OHx8cGFfY29sb3J8fGJlaWdl",
label: "Color",
value: "Beige",
},
{
name: "pa_flavor",
attributeId: 320,
id: "NTY4OHx8cGFfZmxhdm9yfHxnb2xk",
label: "Flavor",
value: "Gold",
},
{
name: "pa_pallet",
attributeId: 337,
id: "NTY4OHx8cGFfcGFsbGV0fHxwZWFjaA==",
label: "Pallet",
value: "Peach",
},
],
},
},
{
attributes: {
nodes: [
{
name: "pa_size",
attributeId: 254,
id: "NTY4OXx8cGFfc2l6ZXx8MTItc3BlYWtlcg==",
label: "Size",
value: '12" Speaker',
},
{
name: "pa_color",
attributeId: 436,
id: "NTY4OXx8cGFfY29sb3J8fGJlbGdyYXZlcw==",
label: "Color",
value: "Belgraves",
},
{
name: "pa_flavor",
attributeId: 319,
id: "NTY4OXx8cGFfZmxhdm9yfHx2YW5pbGxh",
label: "Flavor",
value: "Vanilla",
},
{
name: "pa_pallet",
attributeId: 336,
id: "NTY4OXx8cGFfcGFsbGV0fHxncmVlbg==",
label: "Pallet",
value: "Green",
},
],
},
},
],
},
};
export default function App() {
const [selects, state, setState] = useVariations(product);
function onChange(select, value) {
const newState = {
...state,
[select]: { ...value, name: select },
};
if (!value) {
delete newState[select];
}
setState(newState);
}
return (
<div className="App">
{Object.keys(selects).map((select) => (
<Select
isClearable
key={selects[select].placeholder}
placeholder={selects[select].placeholder}
// value={state[select]}
onChange={(o) => onChange(select, o)}
options={selects[select].options}
/>
))}
</div>
);
}
Playground
Related
I have an array called data. How do i extract sub_data? Just need the sub_data part for each object.
const data = [
{
id: 1,
title: 'Logo'
sub_data: [
{
id: 2,
title: 'Company Logo'
},
{
id: 3,
title: 'Website Logo'
},
]
},
{
id: 2,
title: 'Brands'
sub_data: [
{
id: 25,
title: 'Company Brands'
},
{
id: 3,
title: 'Website Brands'
},
]
}
]
Example output will get two outputs because there is 2 objects:
const subData = [
{
id: 2,
title: 'Company Logo'
},
{
id: 3,
title: 'Website Logo'
},
]
const subData = [
{
id: 25,
title: 'Company Brands'
},
{
id: 3,
title: 'Website Brands'
},
]
Not very sure how to use the map function just to get sub_data in the correct structure
You can use flatMap to get sub_data in one array
const data = [
{
id: 1,
title: 'Logo',
sub_data: [
{
id: 2,
title: 'Company Logo'
},
{
id: 3,
title: 'Website Logo'
},
]
},
{
id: 2,
title: 'Brands',
sub_data: [
{
id: 25,
title: 'Company Brands'
},
{
id: 3,
title: 'Website Brands'
},
]
}
]
const result = data.flatMap(item => item.sub_data)
console.log(result)
If you want an array with the sub_data objects you can just map the original array:
const data = [
{
id: 1,
title: 'Logo',
'sub_data'
: [
{
id: 2,
title: 'Company Logo'
},
{
id: 3,
title: 'Website Logo'
},
]
},
{
id: 2,
title: 'Brands',
sub_data: [
{
id: 25,
title: 'Company Brands'
},
{
id: 3,
title: 'Website Brands'
},
]
}
]
const mappedData = data.flatMap(obj => obj.sub_data)
console.log(mappedData)
Another solution would be to use the .forEach function of javascript.
const subData = [];
data.forEach(item => subData.push(...item.sub_data))
I am trying to get collections using selectors. Here is my code:
Selectors
import { createSelector } from "reselect";
export const selectShop = state => state.shop;
export const selectCollections = createSelector(
[selectShop],
shop => shop.collections
)
export const selectCollectionForPreview = createSelector(
[selectCollections],
collections => Object.keys(collections).map(key => collections[key])
)
export const selectCollectionItem = collectionUrl =>
createSelector(
[selectCollections],
collections => collections[collectionUrl]
//It seems that the selector above is returning collections as an array instead of object, so collections[collectionUrl] is returning undefined
)
Component
const CollectionPage = ({collections}) => {
// const {title, items} = Object.keys(collections)
const {title, items} = collections
console.log('collection', collections);
return(
// <></>
<div className="collection-page">
<h2 className='title'>{title}</h2>
<div className='items'>
{items.map( item =>
<CollectionItem key={item.id} item={item}/>
)}
</div>
</div>
)
}
const mapStateToProps = (state,ownProps) => ({
collections: selectCollectionItem(ownProps.match.params.collectionId)(state)
})
export default connect(mapStateToProps)(CollectionPage);
SHOP_DATA
const SHOP_DATA = {
hats:{
id: 1,
title: 'Hats',
routeName: 'hats',
items: [
{
id: 1,
name: 'Brown Brim',
imageUrl: 'https://i.ibb.co/ZYW3VTp/brown-brim.png',
price: 25
},
{
id: 2,
name: 'Blue Beanie',
imageUrl: 'https://i.ibb.co/ypkgK0X/blue-beanie.png',
price: 18
},
{
id: 3,
name: 'Brown Cowboy',
imageUrl: 'https://i.ibb.co/QdJwgmp/brown-cowboy.png',
price: 35
},
{
id: 4,
name: 'Grey Brim',
imageUrl: 'https://i.ibb.co/RjBLWxB/grey-brim.png',
price: 25
},
{
id: 5,
name: 'Green Beanie',
imageUrl: 'https://i.ibb.co/YTjW3vF/green-beanie.png',
price: 18
},
{
id: 6,
name: 'Palm Tree Cap',
imageUrl: 'https://i.ibb.co/rKBDvJX/palm-tree-cap.png',
price: 14
},
{
id: 7,
name: 'Red Beanie',
imageUrl: 'https://i.ibb.co/bLB646Z/red-beanie.png',
price: 18
},
{
id: 8,
name: 'Wolf Cap',
imageUrl: 'https://i.ibb.co/1f2nWMM/wolf-cap.png',
price: 14
},
{
id: 9,
name: 'Blue Snapback',
imageUrl: 'https://i.ibb.co/X2VJP2W/blue-snapback.png',
price: 16
}
]
},
sneakers:{
id: 2,
title: 'Sneakers',
routeName: 'sneakers',
items: [
{
id: 10,
name: 'Adidas NMD',
imageUrl: 'https://i.ibb.co/0s3pdnc/adidas-nmd.png',
price: 220
},
{
id: 11,
name: 'Adidas Yeezy',
imageUrl: 'https://i.ibb.co/dJbG1cT/yeezy.png',
price: 280
},
{
id: 12,
name: 'Black Converse',
imageUrl: 'https://i.ibb.co/bPmVXyP/black-converse.png',
price: 110
},
{
id: 13,
name: 'Nike White AirForce',
imageUrl: 'https://i.ibb.co/1RcFPk0/white-nike-high-tops.png',
price: 160
},
{
id: 14,
name: 'Nike Red High Tops',
imageUrl: 'https://i.ibb.co/QcvzydB/nikes-red.png',
price: 160
},
{
id: 15,
name: 'Nike Brown High Tops',
imageUrl: 'https://i.ibb.co/fMTV342/nike-brown.png',
price: 160
},
{
id: 16,
name: 'Air Jordan Limited',
imageUrl: 'https://i.ibb.co/w4k6Ws9/nike-funky.png',
price: 190
},
{
id: 17,
name: 'Timberlands',
imageUrl: 'https://i.ibb.co/Mhh6wBg/timberlands.png',
price: 200
}
]
},
jackets:{
id: 3,
title: 'Jackets',
routeName: 'jackets',
items: [
{
id: 18,
name: 'Black Jean Shearling',
imageUrl: 'https://i.ibb.co/XzcwL5s/black-shearling.png',
price: 125
},
{
id: 19,
name: 'Blue Jean Jacket',
imageUrl: 'https://i.ibb.co/mJS6vz0/blue-jean-jacket.png',
price: 90
},
{
id: 20,
name: 'Grey Jean Jacket',
imageUrl: 'https://i.ibb.co/N71k1ML/grey-jean-jacket.png',
price: 90
},
{
id: 21,
name: 'Brown Shearling',
imageUrl: 'https://i.ibb.co/s96FpdP/brown-shearling.png',
price: 165
},
{
id: 22,
name: 'Tan Trench',
imageUrl: 'https://i.ibb.co/M6hHc3F/brown-trench.png',
price: 185
}
]
},
womens:{
id: 4,
title: 'Womens',
routeName: 'womens',
items: [
{
id: 23,
name: 'Blue Tanktop',
imageUrl: 'https://i.ibb.co/7CQVJNm/blue-tank.png',
price: 25
},
{
id: 24,
name: 'Floral Blouse',
imageUrl: 'https://i.ibb.co/4W2DGKm/floral-blouse.png',
price: 20
},
{
id: 25,
name: 'Floral Dress',
imageUrl: 'https://i.ibb.co/KV18Ysr/floral-skirt.png',
price: 80
},
{
id: 26,
name: 'Red Dots Dress',
imageUrl: 'https://i.ibb.co/N3BN1bh/red-polka-dot-dress.png',
price: 80
},
{
id: 27,
name: 'Striped Sweater',
imageUrl: 'https://i.ibb.co/KmSkMbH/striped-sweater.png',
price: 45
},
{
id: 28,
name: 'Yellow Track Suit',
imageUrl: 'https://i.ibb.co/v1cvwNf/yellow-track-suit.png',
price: 135
},
{
id: 29,
name: 'White Blouse',
imageUrl: 'https://i.ibb.co/qBcrsJg/white-vest.png',
price: 20
}
]
},
mens:{
id: 5,
title: 'Mens',
routeName: 'mens',
items: [
{
id: 30,
name: 'Camo Down Vest',
imageUrl: 'https://i.ibb.co/xJS0T3Y/camo-vest.png',
price: 325
},
{
id: 31,
name: 'Floral T-shirt',
imageUrl: 'https://i.ibb.co/qMQ75QZ/floral-shirt.png',
price: 20
},
{
id: 32,
name: 'Black & White Longsleeve',
imageUrl: 'https://i.ibb.co/55z32tw/long-sleeve.png',
price: 25
},
{
id: 33,
name: 'Pink T-shirt',
imageUrl: 'https://i.ibb.co/RvwnBL8/pink-shirt.png',
price: 25
},
{
id: 34,
name: 'Jean Long Sleeve',
imageUrl: 'https://i.ibb.co/VpW4x5t/roll-up-jean-shirt.png',
price: 40
},
{
id: 35,
name: 'Burgundy T-shirt',
imageUrl: 'https://i.ibb.co/mh3VM1f/polka-dot-shirt.png',
price: 25
}
]
}
};
export default SHOP_DATA;
Please provide any pointers or advice on what am I doing wrong? I keep getting the error. It seems that the collection is undefined. I don't understand why. Ideally it should return an object.
You are exporting the component like this
const mapStateToProps = (state,ownProps) => ({
collections: selectCollectionItem(ownProps.match.params.collectionId)(state)
})
export default connect(mapStateToProps)(CollectionPage);
The ownProps.match.params.collectionId might be undefined.
Add this at the top of your file
import { withRouter} from 'react-router-dom'
and export your component like
export default connect(mapStateToProps)(withRouter(CollectionPage));
I have one list look like allsettings. I want to convert that list to a new list. Since I am new to react I don't have much idea, I tried by doing the below way but 1st item in the new list is always empty.
const [mySetting, setMySet] = useState([]);
useEffect(() => {
const allSettings = [
{ name: "Setting1", value: true, label: 1 },
{ name: "Setting2", value: true, label: 2 },
{ name: "Setting3", value: true, label: 3 },
{ name: "Setting4", value: false, label: 4 },
{ name: "Setting5", value: true, label: 5 },
{ name: "Setting6", value: true, label: 6 },
{ name: "Setting7", value: true, label: 7 }
];
const settings = [];
const allSettingsMap = allSettings.reduce((resMap, current) => {
settings.push(resMap);
return {
...resMap,
SettingID: current.label,
Name: current.name,
value: current.value
};
}, {});
setMySet(settings);
}, []);
//I want new list like this:
const newSettings = [
{ name: "Setting1", value: true, SettingID: 1 },
{ name: "Setting2", value: true, SettingID: 2 },
{ name: "Setting3", value: true, SettingID: 3 },
{ name: "Setting4", value: false, SettingID: 4 },
{ name: "Setting5", value: true, SettingID: 5 },
{ name: "Setting6", value: true, SettingID: 6 },
{ name: "Setting7", value: true, SettingID: 7 }
];
You can use array#map to rename a key in your object and keeping other keys intact. For each object, you can pick label and rename it to SettingID and keep other key-values same.
const allSettings = [ { name: "Setting1", value: true, label: 1 }, { name: "Setting2", value: true, label: 2 }, { name: "Setting3", value: true, label: 3 }, { name: "Setting4", value: false, label: 4 }, { name: "Setting5", value: true, label: 5 }, { name: "Setting6", value: true, label: 6 }, { name: "Setting7", value: true, label: 7 } ],
result = allSettings.map(({label, ...other}) => ({...other, SettingID: label}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can easily do it by map on array
const allSettings = [
{ name: "Setting1", value: true, label: 1 },
{ name: "Setting2", value: true, label: 2 },
{ name: "Setting3", value: true, label: 3 },
{ name: "Setting4", value: false, label: 4 },
{ name: "Setting5", value: true, label: 5 },
{ name: "Setting6", value: true, label: 6 },
{ name: "Setting7", value: true, label: 7 }
];
const newAllSettings = allSettings.map(item => {
return {
name: item.name,
value: item.value,
SettingID:item.label
};
});
console.log(newAllSettings)
Replace your allSettings.reduce method with this map method
const settings = [];
allSettings.map((setting) => {
const item = { ...setting };
const tempValue = item?.label;
// delete item label
delete item["label"];
item["SettingID"] = tempValue;
settings.push(item);
});
The arrays I have
const users = [
{ id: 1, name: "field 1" },
{ id: 2, name: "field 2" },
{ id: 3, name: "field 3" },
{ id: 4, name: "field 4" },
];
const onlineUsers = [
{ id: 1, name: "field 1" },
{ id: 3, name: "field 3" }
];
I would like to find the online and offline ones by comparing the two series
I want to do:
const userLists = [
{ id: 1, name: "field 1", online: true },
{ id: 2, name: "field 2", online: false },
{ id: 3, name: "field 3", online: true },
{ id: 4, name: "field 4", online: false },
];
Using Array.map and Array.some
const users = [
{ id: 1, name: "field 1" },
{ id: 2, name: "field 2" },
{ id: 3, name: "field 3" },
{ id: 4, name: "field 4" },
];
const onlineUsers = [
{ id: 1, name: "field 1" },
{ id: 3, name: "field 3" }
];
var retVal=users.map(u=>{
var isOnline=onlineUsers.some(ou=> ou.id==u.id);//this will check if onlineUsers have some record with given userid
return {...u,online:isOnline}
})
console.log(retVal)
You can just traverse through the user list and you can find out the onlineuser using find and just push it in the onlineuserList.
const users = [
{ id: 1, name: "field 1" },
{ id: 2, name: "field 2" },
{ id: 3, name: "field 3" },
{ id: 4, name: "field 4" },
];
const onlineUsers = [
{ id: 1, name: "field 1" },
{ id: 3, name: "field 3" }
];
const userLists = [];
users.forEach(user => {
if(onlineUsers.find(q => q.id == user.id)){
userLists.push({
id: user.id,
name: user.name,
online: "true"
})
}
else{
userLists.push({
id: user.id,
name: user.name,
online: "false"
})
}
})
console.log(userLists);
a bit faster approach using Array.indexOf() and JSON.strigify()
const onlineUsers = JSON.stringify([
{ id: 1, name: "field 1" },
{ id: 3, name: "field 3" }
]);
const userList = users.map(user =>
({
...user,
online: onlineUsers.indexOf(JSON.stringify(user)) > -1
})
);
OR if you neither want to change original onlineUsers array nor declare another variable:
const userList = users.map(user =>
({ ...user, online: JSON.stringify(onlineUsers).indexOf(JSON.stringify(user)) > -1 })
);
componentDidMount(){
this.setState({
values2:[{ name: 'Q1', id: 1 },
{ name: 'Q2', id: 2 },
{ name: 'Q3', id: 3 },
{ name: 'Q4', id: 4 }]
});
}
setQuarterData(){
var optionTemplate2 = this.state.values2.map(v => (
<option value={v.id} key={v.id}>{v.name}</option>
));
document.getElementById('quarter').innerHTML(optionTemplate2);
// document.getElementById('quarter').style.background="red";
console.log(optionTemplate2);
}
i am getting data in optionTemplate2 , but i unable to set in select
0: {$$typeof: Symbol(react.element), type: "option", key: "1", ref: null, props: {…}, …}
1: {$$typeof: Symbol(react.element), type: "option", key: "2", ref: null, props: {…}, …}
2: {$$typeof: Symbol(react.element), type: "option", key: "3", ref: null, props: {…}, …}
3: {$$typeof: Symbol(react.element), type: "option", key: "4", ref: null, props: {…}, …}
length: 4
proto: Array(0)
i want to set it here:-
<Form.Group>
<Form.Label>Quarters</Form.Label>
<Form.Control as="select" id="quarter">
</Form.Control>
</Form.Group>
class FirstComponent extends React.Component{
constructor(props){
super(props);
let todayDate = new Date();
this.state = {
finsclYear: [
{ name: '2014-2015', id: "2014-03-31"},
{ name: '2016-2017', id: "2016-03-31" },
{ name: '2017-2018', id: "2017-03-31" },
{ name: '2018-2019', id: "2018-03-31" },
{ name: '2019-2020', id: todayDate}
],
quarter:[ ],
chartData:chartData[0],
tableData: FilterTableCustom
};
this.setQuarterData=this.setQuarterData.bind(this);
this.changeData=this.changeData.bind(this);
}
setQuarterData(el){
let value=el.target.value;
let quarter;
let today = new Date(value);
let month=today.getMonth();
//calculating quarter for financial year
if(month<12 && month>2){
quarter = Math.floor(month / 3);
}
else{
quarter = Math.floor((month+12) / 3);
}
let list2=document.getElementById("quarter");
switch(quarter){
case 1:
this.setState({
quarter:[{ name: 'Q1', id: 1 } ]
});
break;
case 2:
this.setState({
quarter:[{ name: 'Q1', id: 1 },
{ name: 'Q2', id: 2 } ]
});
break;
case 3:
this.setState({
quarter:[{ name: 'Q1', id: 1 },
{ name: 'Q2', id: 2 },
{ name: 'Q3', id: 3 }]
});
break;
case 4:
this.setState({
quarter:[{ name: 'Q1', id: 1 },
{ name: 'Q2', id: 2 },
{ name: 'Q3', id: 3 },
{ name: 'Q4', id: 4 }]
});
break;
default :
null
}
}
changeData(){
this.setState({
chartData:chartData2[0],
tableData: FilterTableCustom2
});
}
render(){
const {tableData}=this.state;
const {chartData}=this.state;
console.log(tableData);
const {quarter} =this.state;
let finsclYearData = this.state.finsclYear.map(v => (
<option value={v.id} key={v.id}>{v.name}</option>
));
let quarterData="";
if(quarter.length!=0){
quarterData =quarter.map(v => (
<option value={v.id} key={v.id}>{v.name}</option>
));
}