简体   繁体   English

如何通过退出 object 创建新对象(数组)?

[英]How can I create new object(array) by exiting object?

I have object as following:我有object如下:

0 : {rYear: '1Y', rType: 'TypeA', rVal: 41}
1 : {rYear: '2Y', rType: 'TypeA', rVal: 11}
2 : {rYear: '3Y', rType: 'TypeA', rVal: 32}
3 : {rYear: '1Y', rType: 'TypeB', rVal: 12}
4 : {rYear: '2Y', rType: 'TypeB', rVal: 21}
5 : {rYear: '3Y', rType: 'TypeB', rVal: 16}

I want to transfer the object as below format:我想按以下格式传输object

0 : {rType: 'TypeA', 1Y: 41, 2Y: 11, 3Y: 32}
1 : {rType: 'TypeB', 1Y: 12, 2Y: 21, 3Y: 16}

I've tried to use .groupBy(collection, [iteratee= .identity]) from lodash , but dose not get what I need to achieve.我尝试使用lodash 中的 .groupBy(collection, [iteratee= .identity ]) ,但没有得到我需要实现的目标。

You could use a simple reduce to group the objects based on rType :您可以使用简单的reduce来根据rType对对象进行分组:

 const input = [ { rYear: '1Y', rType: 'TypeA', rVal: 41 }, { rYear: '2Y', rType: 'TypeA', rVal: 11 }, { rYear: '3Y', rType: 'TypeA', rVal: 32 }, { rYear: '1Y', rType: 'TypeB', rVal: 12 }, { rYear: '2Y', rType: 'TypeB', rVal: 21 }, { rYear: '3Y', rType: 'TypeB', rVal: 16 }, ] const grouped = input.reduce((acc, { rYear, rType, rVal }) => { acc[rType]??= { rType }; acc[rType][rYear] = rVal return acc }, {}) const output = Object.values(grouped) console.log(output)

We can do it just by using Array.reduce()我们可以通过使用Array.reduce()完成

 let data = [ {rYear: '1Y', rType: 'TypeA', rVal: 41}, {rYear: '2Y', rType: 'TypeA', rVal: 11}, {rYear: '3Y', rType: 'TypeA', rVal: 32}, {rYear: '1Y', rType: 'TypeB', rVal: 12}, {rYear: '2Y', rType: 'TypeB', rVal: 21}, {rYear: '3Y', rType: 'TypeB', rVal: 16} ] let result = data.reduce((a,v) =>{ let obj = a.find(i => i.rType === v.rType) if(obj){ obj[v.rYear] = v.rVal }else{ obj = {'rType':v.rType} obj[v.rYear] = v.rVal a.push(obj) } return a },[]) console.log(result)

when I got a logic like this, I usually use a map to solve the problem.当我得到这样的逻辑时,我通常会使用一个 map 来解决问题。 Like the following code.就像下面的代码。

 const arr = [ { rYear: "1Y", rType: "TypeA", rVal: 41 }, { rYear: "2Y", rType: "TypeA", rVal: 11 }, { rYear: "3Y", rType: "TypeA", rVal: 32 }, { rYear: "1Y", rType: "TypeB", rVal: 12 }, { rYear: "2Y", rType: "TypeB", rVal: 21 }, { rYear: "3Y", rType: "TypeB", rVal: 16 }, ]; const objMap = new Map(); arr.forEach((e) => { const obj = {}; obj[e.rYear] = e.rVal; obj["rType"] = e.rType; if (objMap.get(e.rType) === undefined) { objMap.set(e.rType, obj); } objMap.get(e.rType)[e.rYear] = e.rVal; }); const resultArr = []; objMap.forEach((e) => { resultArr.push(e); });

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

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