繁体   English   中英

Javascript中优雅的数组转换

[英]Elegant array transformation in Javascript

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

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' }
]

进入:

var out = [
  { a: 1, x: 'foo', y: 'goo' },
  { a: 2, x: 'hoo', y: 'joo' }
]

的逻辑是,所有内容应基于它们被接合a属性,并且所有bc性质分别表示键/值对应合并成基于它们共享的单个对象a值。

您可以使用哈希对象,并使用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[oa] = hash[oa] || {a: oa}; // if there is no object in the hash that have the value of the key a equal to oa, then create a new one hash[oa][ob] = oc; // set the value of the key stored in ob to oc return hash; }, {}) ); console.log(result); 

你可以使用带有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(oa) && map.set(oa, r[r.push({ a: oa }) - 1]), map.get(oa)[ob] = oc, r))(new Map), []); console.log(output); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

您可以使用forEachObject.assigna进行分组,然后map以返回对象值。

 var data = [ { a: 1, b: 'x', c: 'foo' }, { a: 1, b: 'y', c: 'goo' }, { a: 2, b: 'x', c: 'hoo' }, { a: 2, b: 'y', c: 'joo' } ] var r = {} data.forEach(e => r[ea] = Object.assign((r[ea] || {}), {a: ea, [eb]: ec})) r = Object.keys(r).map(e => r[e]) console.log(r) 

不确定方法是优雅还是功能,但使用for..of循环返回预期结果, Array.prototype.some()Object.assign()

 function props(array, key, prop1, prop2) { let arr = []; for (let obj of array) { let o = {}; for (let {[key]:_key, [prop1]:_prop1, [prop2]:_prop2} of [obj]) { o[_prop1] = _prop2; o[key] = _key; } if (!arr.some(p => p[key] === o[key])) arr.push(o); for (let prop of arr) { if (prop[key] == o[key]) { prop = Object.assign(prop, o) } } } return arr } 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' } ]; console.log(props(_in, "a", "b", "c")); 

我喜欢提供的答案,但这是我的尝试。 我相信它更具可读性,但它使用Object.assignObject.values

const 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' }
]

const map = input.reduce((acc, obj) => {
  const [a, key, value] = Object.values(obj)
  const newObj = {a, [key]: value}

  if (acc[a]) {
    Object.assign(acc[a], newObj)
  } else {
   acc[a] = newObj
  }

  return acc 
}, {})

console.log(Object.values(map))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM