javascript - 试图“映射”嵌套的 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>
提前感谢您的时间和考虑。
解决方案
将数组视为一个对象。它以类似的方式访问,所以如果它是一个对象,它将是这样的:
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);
推荐阅读
- neo4j - 生成嵌套递归 json 的密码请求
- swift - 如何使用 Swift 编辑和更新 xml 文件
- c# - 使用 docker 容器中的 api 网关而不是 localhost:port 进行导航
- angular - Angular ngIf 两个变量相同(字符串和数字)
- xamarin - 如何在 Xamarin 中创建按类别分组的问卷?
- ios - 上传图片时iOS应用WKWebView错误
- xamarin - Xamarin UI 测试
- postgresql - Sequelize 查询,其中记录在相关表中不存在或在相关表中存在条件
- python - Python Dataframe-如何对包含年、月、日数据的三个不同列进行分组并从第四列计算总和
- python - 为什么在 python 中使用 re.split() 时会得到那些空字符串?