如何映射对象的多个数据?

时间:2019-02-19 12:11:45

标签: jquery object join

这个...

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

错误:

  

SyntaxError:缺少)(括号中)

1 个答案:

答案 0 :(得分:3)

您接近了!使用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>