使用map函数在Javascript中创建关联数组

Eze*_*nda 10 javascript arrays associative-array map-function

我有一个具有以下格式的对象数组

[{'list': 'one', 'item': 1}, 
 {'list': 'one', 'item': 2},
 {'list': 'one', 'item': 3},
 {'list': 'two', 'item': 1},
 {'list': 'two', 'item': 2}]
Run Code Online (Sandbox Code Playgroud)

我想像这样改造它

[{'one': [1, 2, 3]},
 {'two': [1, 2]}]
Run Code Online (Sandbox Code Playgroud)

我怎么能用Array.map函数呢?这是最好的选择吗?

Nin*_*olz 12

您可以使用Array.prototype.reduce您的任务.它允许回调函数中的返回值用于下一次调用.

var data = [
        { 'list': 'one', 'item': 1 },
        { 'list': 'one', 'item': 2 },
        { 'list': 'one', 'item': 3 },
        { 'list': 'two', 'item': 1 },
        { 'list': 'two', 'item': 2 }
    ],
    flat = data.reduce(function (r, a) {
        r[a.list] = r[a.list] || [];
        r[a.list].push(a.item);
        return r;
    }, {});

document.write('<pre>' + JSON.stringify(flat, 0, 4) + '</pre>');
Run Code Online (Sandbox Code Playgroud)


Ram*_*ony 2

对于你的具体问题:

// Let x hold your array of objects.

res={}; // Create an empty object that will hold the answer

x.forEach (function (e) { // Use this function to iterate over each item in the list
    res[e.list] = res[e.list] || [];   // inspired by the Nina Scholz answer below
    res[e.list].push(e.item);   // Append the result to the array
 });
Run Code Online (Sandbox Code Playgroud)

  • 您应该接受下面尼娜·肖尔茨的回答。它很优雅,不会改变结果变量,并提供“reduce”,这是非常值得学习的。当/如果你选择函数式编程时它会派上用场。 (2认同)