簡體   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