A list is coming from the backend.
response;
activePoliciesMap:
OTHER: Array(3)
0: {policyNumber: '1184140022', …}
1: {policyNumber: '1272731122', …}
2: {policyNumber: '100091622', …}
length: 3
PET: Array(1)
0: {policyNumber: '1272741022', …}
length: 1
RESIDENCE: Array(2)
0: {policyNumber: '1277976920', …}
1: {policyNumber: '1064318822', …}
length: 2
TRAVEL: Array(1)
0: {policyNumber: '1271732822', …}
length: 1
I want to print all of them, regardless of the type of product.
I tried to convert the values inside the object to array. But I was not successful.
const activePolicyList = [];
useEffect(() => {
if (props.activePolicy !== undefined) {
Object.values(props.activePolicy).map((policyType) => {
Object.values(policyType).map((policyList) => {
policyList.map((policy) => {
if (activePolicyList.length === 0) {
activePolicyList.push({
policy
});
}
});
});
});
}
console.log(activePolicyList);
}, []);
After running this code I am only able to display a single element.
I can view;
0:
policy:
policyNumber: "1277976920"
For Example; I want to print on cards like in the picture.
How can I collect all the elements in a single list?
CodePudding user response:
Assuming your props.activePolicy
is the object { activePoliciesMap: {...} }
useEffect(() => {
let activePolicyList = [];
if (props.activePolicy !== undefined) {
Object.values(props.activePolicy.activePoliciesMap).forEach((policies) => {
activePolicyList = activePolicyList.concat(policies);
});
}
console.log(activePolicyList);
}, []);
CodePudding user response:
you can use Object.entries
and flatMap
for that
const data = {
activePoliciesMap: {
OTHER: [
{policyNumber: '1184140022'},
{policyNumber: '1272731122'},
{policyNumber: '100091622'}
],
PET:[
{policyNumber: '1272741022'}
],
RESIDENCE: [
{policyNumber: '1277976920'},
{policyNumber: '1064318822'}
],
TRAVEL:[
{policyNumber: '1271732822'}
]}
}
const active = Object.entries(data.activePoliciesMap).flatMap(([_, p]) => p)
console.log(active)
I suggest you to store those data into a state like this
const [active, setActive] = useState([])
useEffect(() => {
if(!data.activePoliciesMap) return;
setActive(Object.entries(data.activePoliciesMap).flatMap(([_, p]) => p))
}, [data])