这个...
return (data.map(obj => obj.name)).join('<br>');
...给我输出:
monkey
cat
snake
elephant
和这个..
return (data.map(obj => obj.group.id)).join('<br>');
...给我输出:
2
4
6
3
我需要的输出是:
id: 2, name: monkey
id: 4, name: cat
id: 6, name: snake
id: 3, name: elephant
这是我的方法:
return ('id:' + data.map(obj => obj.group.id) + ', name: 'data.map(obj => obj.name)).join('<br>');
错误:
括号中的语法错误:缺少)
最佳答案
你近了!使用template strings使工作容易得多。
const data = [
{
name: "monkey",
group: {
id: "2"
}
},
{
name: "cat",
group: {
id: "4"
}
},
{
name: "snake",
group: {
id: "6"
}
},
{
name: "elephant",
group: {
id: "3"
}
}
];
const joined = data.map(obj => `id: ${obj.group.id}, name: ${obj.name}`).join('<br>');
document.getElementById("app").innerHTML = joined;
<div id="app"></div>
关于jquery - 如何映射对象的多个数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54766061/