首页 > 解决方案 > 试图“映射”嵌套的 JSON 元素对象(javascript)

问题描述

我正在尝试“映射”具有对象的嵌套 JSON 元素以构建 HTML。我不确定我在语法上做错了什么,如下所示:

    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>

提前感谢您的时间和考虑。

标签: javascripttemplate-literals

解决方案


将数组视为一个对象。它以类似的方式访问,所以如果它是一个对象,它将是这样的:

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

因此,要直接访问它的第一个元素,您需要:

array1[0].things

要获得您想要的结果,您需要执行以下操作:

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);

如果您的数组可以有多个元素,您可以使用以下内容:

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);


推荐阅读