Javascript中优雅的数组转换

Yuv*_*dam 5 javascript ecmascript-6

什么是一种优雅的方式 - 纯粹的功能,理想情况下 - 转换(减少?)这个数组:

var in = [
  { a: 1, b: 'x', c: 'foo' },
  { a: 1, b: 'y', c: 'goo' },
  { a: 2, b: 'x', c: 'hoo' },
  { a: 2, b: 'y', c: 'joo' }
]
Run Code Online (Sandbox Code Playgroud)

进入:

var out = [
  { a: 1, x: 'foo', y: 'goo' },
  { a: 2, x: 'hoo', y: 'joo' }
]
Run Code Online (Sandbox Code Playgroud)

逻辑是所有元素都应该基于它们的a属性连接,并且所有bc属性分别表示应该基于它们的共享a值合并到单个对象中的键/值对.

ibr*_*rir 8

您可以使用哈希对象,并reduce像这样包装哈希:

const arr = [
  { a: 1, b: 'x', c: 'foo' },
  { a: 1, b: 'y', c: 'goo' },
  { a: 2, b: 'x', c: 'hoo' },
  { a: 2, b: 'y', c: 'joo' }
];

let result = Object.values(             // the result is the values of the hash object
  arr.reduce((hash, o) => {             // hash is a hash object that make it easier to group the result
    hash[o.a] = hash[o.a] || {a: o.a};  // if there is no object in the hash that have the value of the key a equal to o.a, then create a new one
    hash[o.a][o.b] = o.c;               // set the value of the key stored in o.b to o.c
    return hash;
  }, {})
);

console.log(result);
Run Code Online (Sandbox Code Playgroud)

  • @Bergi我一直在犹豫.我将删除第一个并保留第二个.它更优雅_这就是OP所要求的! (2认同)

Nin*_*olz 5

你可以使用一个封闭 Map

var input = [{ a: 1, b: 'x', c: 'foo' }, { a: 1, b: 'y', c: 'goo' }, { a: 2, b: 'x', c: 'hoo' }, { a: 2, b: 'y', c: 'joo' }],
    output = input.reduce((map => (r, o) => (!map.has(o.a) && map.set(o.a, r[r.push({ a: o.a }) - 1]), map.get(o.a)[o.b] = o.c, r))(new Map), []);

console.log(output);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)