gpt4 book ai didi

javascript - 尝试 'map' 嵌套 JSON 元素对象(javascript)

转载 作者:行者123 更新时间:2023-12-02 22:06:24 25 4
gpt4 key购买 nike

我正在尝试“映射”具有对象的嵌套 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>

预先感谢您的时间和考虑。

最佳答案

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

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

关于javascript - 尝试 'map' 嵌套 JSON 元素对象(javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59701435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com