简体   繁体   English

如何转换JavaScript数组

[英]How to transform javascript array

I have got an array: 我有一个数组:

var tab = [];

          tab.push({key: 1,value: usa});
          tab.push({key: 2,value: germany});
          tab.push({key: 1,value: india});
          tab.push({key: 1,value: russsia});
          tab.push({key: 2,value: poland});
          tab.push({key: 1,value: uk});

And what I'm trying to do is to transform above array to receive: 我想做的就是将上述数组转换为接收:

[{"1":"usa,india,russia,uk"},
{"2":"germany,poland"}]

I'd like to have unique values in key field, and aggregate values from value fields. 我想在键字段中具有唯一值,并从值字段中聚合值。

How to achive this? 如何做到这一点?

 var tab = []; tab.push({key: 1,value: 'usa'}); tab.push({key: 2,value: 'germany'}); tab.push({key: 1,value: 'india'}); tab.push({key: 1,value: 'russsia'}); tab.push({key: 2,value: 'poland'}); tab.push({key: 1,value: 'uk'}); var transformedObject = {}; tab.forEach(function (item) { transformedObject[item.key] = transformedObject[item.key] ? `${transformedObject[item.key]}, ${item.value}` : item.value; }); console.log(transformedObject); // Access the '2' property console.log(transformedObject['2']); 

Using reduce : 使用reduce

 const orig = [{ key: 1, value: 'usa' }, { key: 1, value: 'russia' }, { key: 2, value: 'uk' }]; const result = orig.reduce((red, el) => { if (red[el.key] !== undefined) { red[el.key] += `, ${el.value}`; } else { red[el.key] = el.value; } return red; }, {}); console.log(result); 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

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

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