Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
959 views
in Technique[技术] by (71.8m points)

我想把两个json合并在一起

我想得到一个这样的json

[
              {'id':1,'array1':2,'array2':3,'array3':4},
              {'id':2,'array1':3,'array2':4},
              {'id':3,'array1':4,'array2':5,'array3':6,'array4':7,'array5':8}
  ]

根据通过两个不同json下的id关联在一起。
jsonA:

[{'id':1},{'id':2},{'id':3}]

jsonB:

 [
              {'id':1,'array':[2,3,4]},
              {'id':2,'array':[3,4]},
              {'id':3,'array':[5,6,7,8]}
  ]

我该怎么实现呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
const a = [{ id: 1 }, { id: 2 }, { id: 3 }];
const b = [
  { id: 1, array: [2, 3, 4] },
  { id: 2, array: [3, 4] },
  { id: 3, array: [5, 6, 7, 8] }
]


function Combiner(target, data) {
  return target.reduce((pre, cur) => {
    // find
    const matchData = data.find(i => i.id === cur.id)
    // generate array${index}
    const generator = (arr = []) => {
      return arr.reduce((pre, cur, index) => {
        return {
          ...pre,
          [`array${index + 1}`] : arr[index]
        }
      }, {})
    }
    // fill min to max
    const justifyScope = (start, arr) => {
      let gap = arr[0] - start
      if (gap <= 1) {
        return arr
      }
      while(gap > 1) {
        arr.unshift(arr[0] - 1)
        gap--
      }
      return arr
    }
    const newData = matchData ? {
      ...cur,
      ...generator(justifyScope(cur.id, [...matchData.array.sort()]))
    } : cur
    return [
      ...pre,
      newData
    ]
  }, [])
}
console.log(Combiner(a, b))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...