Reputation: 478
My data look like this:
and my code looks like this:
const navItemData = props.data.navigation_bar;
let temporaryDrawers = [];
if (navItemData) {
for (let i = 0; i < navItemData.length; i++) {
if (navItemData[i].object_type === 'temporary_drawer') {
temporaryDrawers.push(navItemData[i]);
// CODE HERE
}
}
}
This is the log of my temporaryDrawers
array:
I want to say in the //CODE HERE
that:
if (navigation_bar.content === data.key with the same name e.g. 'products')
then temporaryDrawers.push the array 'products'
and the result that I'm expecting is to get a temporaryDrawers
array that looks like this:
This is my data structure:
{
"website": {
"navigation_bar": [
{
"object_type": "temporary_drawer",
"title": "Products",
"content": "products"
},
{
"object_type": "temporary_drawer",
"title": "Resources",
"content": "resources"
},
{
"object_type": "navigation_button",
"title": "Pricing",
"link": "/pricing"
}
],
"products": [
{
"name": "Lorem ipsum",
"description": "Lorem ipsum dolor sit amet",
"image": "/mockImage1.png"
},
{
"name": "Lorem ipsum",
"description": "Lorem ipsum dolor sit amet",
"image": "/mockImage2.png"
},
{
"name": "Lorem ipsum",
"description": "Lorem ipsum dolor sit amet",
"image": "/mockImage3.png"
},
{
"name": "Lorem ipsum dolor",
"description": "Lorem ipsum dolor sit amet",
"image": "/mockImage4.png"
}
]
}
}
How can I do this?
Upvotes: 1
Views: 117
Reputation: 604
I think this can help. You are dynamically creating a property that reflects the string under 'content'. Next, you are using the same string as a key in the data object in order to attach a list to the created property
if (navItemData) {
for (let i = 0; i < navItemData.length; i++) {
if (navItemData[i].object_type === 'temporary_drawer') {
const item = navItemData[i];
temporaryDrawers.push({...item, [item.content]: props.data[item.content]});
}
}
}
Upvotes: 4