Search code examples
javascripttemplate-literals

Trying to 'map' nested JSON element object (javascript)


I am trying to 'map' nested JSON elements that have objects in order to build HTML. I am not sure what I am doing wrong with the syntax as follows:

    array1 = [
      {
        "name":"test",
        "things": [
          { "name":"thing1" },
          { "name": "thing2"}
        ]
      }
    ];

    const createThingy = (item) => `
        <p>${item.name}</p>
    `

    // pass a function to map
    const map1 = array1.things.map(createThingy).join('');
    console.log(array1);

    // expected output: <p>thing1</p><p>thing2</p>

Thank you in advance for your time and consideration.


Solution

  • Think of the array as an object. It's accessed in a similar way, so if it were an object it would be like this:

    let array1 = {
      0: {
        "name":"test",
        "things": [
          { "name": "thing1" },
          { "name": "thing2" }
        ]
      }
    };
    

    Therefore, to access its first element directly you need:

    array1[0].things
    

    To get your desired outcome you need to the following:

    let array1 = [
      {
        "name": "test",
        "things": [
          { "name": "thing1" },
          { "name": "thing2" }
        ]
      }
    ];
    
    const createThingy = (item) => `
      <p>${item.name}</p>
    `;
    
    // pass a function to map
    const map1 = array1[0].things.map(createThingy).join('');
    console.log(map1);

    In case your array can have multiple elements, you can use the following:

    let array1 = [
      {
        "name": "test",
        "things": [
          { "name": "thing1" },
          { "name": "thing2" }
        ]
      }
    ];
    
    const createThingy = (item) => `
      <p>${item.name}</p>
    `;
    
    // pass a function to map
    const map1 = array1.reduce((acc, elem) => acc + elem.things.map(createThingy).join(''), "");
    console.log(map1);