首页 > 解决方案 > 如何使用 Lodash.js 对集合/数组进行反透视?

问题描述

我是 JavaScript 的初学者,我想取消一个集合/数组。

我有一个这样的集合/数组:

[
  { 'produit': 'a', 'color': 'white', 'material': 'leather' }, 
  { 'produit': 'b', 'attribute': 'black', 'material': 'wool' }
]

我想转换我的集合/数组以获得这样的东西:

var a = [
  { 'produit': 'a', 'attribute': 'color', 'value': 'white' }, 
  { 'produit': 'a', 'attribute': 'material', 'value': 'leather' }, 
  { 'produit': 'b', 'attribute': 'color', 'value' :'black' },
  { 'produit': 'b', 'attribute': 'material', 'value': 'wool' }
]

我试图在 lodash.js 的文档中找到一些东西,但我不知道该怎么做。

标签: javascriptlodashunpivot

解决方案


您可以使用_.flatMap(), 通过解构每个对象的键produit,然后将剩余对象的键/值映射到一个新对象,该对象包括键,键作为键,值作为键:produitattributevalue

const arr = [
  { 'produit': 'a', 'color': 'white', 'material': 'leather' }, 
  { 'produit': 'b', 'attribute': 'black', 'material': 'wool' }
];

const res = _.flatMap(
  arr,
  ({produit, ...r}) => _.map(_.entries(r), ([attribute, value]) => ({produit, attribute, value}))
);

console.log(res);
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>

现在 JS 有很多内置的数组函数,所以在 vanilla JS 中也可以使用类似的方法实现上述功能:

const arr = [
  { 'produit': 'a', 'color': 'white', 'material': 'leather' }, 
  { 'produit': 'b', 'attribute': 'black', 'material': 'wool' }
];

const res = arr.flatMap(
  ({produit, ...r}) => Object.entries(r).map(([attribute, value]) => ({produit, attribute, value}))
);

console.log(res);
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>


推荐阅读