javascript - 带有对象变换的数组

标签 javascript arrays

我有一个包含如下对象的数组:

arr = [
  {name: 'Igor', id: 1,....},
  {name: 'Anton', id: 1,.... },
  {name: 'Igor', id: 2,.... },
  {name: 'Peter', id: 2,.... },
  {name: 'Igor', id: 2,.... }
]

我需要获取新的数组,例如:

arrId = [
  { id: 1, names: 'Igor, Anton' },
  { id: 2, names: 'Igor, Peter' }
]

想不出好的解决办法

最佳答案

在此示例中,我使用 mapreduce .

function rearrange(arr) {

  // use `reduce` to build an object using the ids as keys
  // this allows us to place all the names with the same id together
  // note we pass in an empty object to act as our initial p argument.
  var out = arr.reduce(function (p, c) {
    var key = c.id, name = c.name;

    // if the key doesn't exist create it and set its value
    // to an empty array
    p[key] = p[key] || [];

    // add the name to the array if it doesn't already exist
    if (p[key].indexOf(name) === -1) p[key].push(name);
    return p;
  }, {});

  // use `map` to return an array of objects
  return Object.keys(out).map(function (el) {

    // make sure we use an integer for the id, and
    // join the array to get the appropriate output
    return { id: +el, names: out[el].join(', ') };
  });

}

rearrange(arr);

DEMO

输出

[
  {
    "id": 1,
    "names": "Igor, Anton"
  },
  {
    "id": 2,
    "names": "Igor, Peter"
  }
]

关于javascript - 带有对象变换的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34351086/

相关文章:

mysql - 从多维数组获取值 | JSON

javascript - mootools: $ 未定义

javascript - Vue.js 2 自动转义 HTML

javascript - WebStorm/usr/local/bin/node --debug-brk=55834 --nolazy app.js

php - 在 laravel 中合并两个数组值

python - 如何初始化具有给定维数的空 Numpy 数组?

javascript - AJAX 成功后如何关闭模态窗口

javascript - ng-focus 触发两次,而 ng-blur 从不触发

php - 将两个数组合并为 PHP 中的键值对

Javascript: 'new Array(4)' 与 Array.apply(null, {length: 4}) 有何不同?