Home > OS >  Loop through an array of nested objects in javascript
Loop through an array of nested objects in javascript

Time:11-30

Im having trouble to print out objects that are inside of an array, When im console logging this is what i get:

console.log(product.categories)

How would i be able to iterate through these nested objects where i could display these individually like

<ul>
  <li>Bath</li>
  <li>/bath/</li>
  <li>18</li>
  <li>Shop all</li>
  <li>/shop-all/</li>
  <li>23</li>
</ul>

The whole 'products' data object looks like this enter image description here

CodePudding user response:

You can loop over the values of each object in the array, create list items from each of them, and append them to the list element.

let obj = {
  edges: [
    {name: 'Bath', path: '/bath/', entityId: 18},
    {name: 'Shop App', path: '/shop-all/', entityId: 23}
  ]
}
let ul = document.createElement('ul');
for(const x of obj.edges) 
  for(const textContent of Object.values(x))
    ul.append(Object.assign(document.createElement('li'), {textContent}));
document.body.append(ul);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

2 Ways


There are 2 solutions I can think of at the moment.

<Array>.forEach()


This solution is best if you want to log the individual elements of the array.
There's a better way for changing the array elements but let's look at the example.

const arr = [{ name: "Home", path: "/home" }, { name: "Forums", path: "/forums" }];

arr.forEach((value) => {
    console.log(value);
});
// { name: "Home", path: "/home" }
// { name: "Forums", path: "/forums" }


// You can map it to a new value by doing this

const newArr = [];

arr.forEach((value) => {
    newArr.push(value.name);
});

console.log(newArr);
// ["Home", "Forums"]

<Array>.map()


This is the best solution I would use.
This method changes the value of individual element to what returns in your function.

const arr = [{ name: "Home", path: "/home" }, { name: "Forums", path: "/forums" }];

const newArr = arr.map((value) => value.name);
console.log(newArr);

// ["Home", "Forums"]
// Notice how the value has changed


The Solution

Here's what the solution will look like

function YourComponent() {
    const edges = product.categories.edges;
    const products = edges.map((value) => [value.name, value.path, value.entityId.toString()]);

    return (
        {
            products.map((data) => {
                return (
                    <li>data[0]</li>
                    <li>data[1]</li>
                    <li>data[2]</li>
                );
            });
        }
    );
};
  • Related