首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用Lodash.js取消透视集合/数组?

如何使用Lodash.js取消透视集合/数组?
EN

Stack Overflow用户
提问于 2020-09-30 23:57:11
回答 2查看 55关注 0票数 0

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

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

代码语言:javascript
复制
[
  { 'produit': 'a', 'color': 'white', 'material': 'leather' }, 
  { 'produit': 'b', 'attribute': 'black', 'material': 'wool' }
]

我想转换我的集合/数组,以获得如下所示:

代码语言:javascript
复制
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的文档中找到一些东西,但是我不知道怎么做。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-10-01 00:08:01

您可以使用_.flatMap(),方法是为每个对象destructuring produit键,然后将剩余对象的keys/values mapping到一个新对象,其中包括produit键,键作为attribute键,值作为value键:

代码语言:javascript
复制
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);
代码语言:javascript
复制
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>

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

代码语言:javascript
复制
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);
代码语言:javascript
复制
<script src="https://cdn.jsdelivr.net/lodash/4.16.4/lodash.min.js"></script>

票数 1
EN

Stack Overflow用户

发布于 2020-10-01 00:09:35

您不需要使用lodash来完成此操作。您可以使用对象销毁和缩减轻松完成此操作。

代码语言:javascript
复制
const original = [
  { 'produit': 'a', 'color': 'white', 'material': 'leather' }, 
  { 'produit': 'b', 'attribute': 'black', 'material': 'wool' }
]

const altered = original.reduce((acc, item) =>
  (({ produit, ...rest }) =>
    Object.entries(rest).reduce((result, [attribute, value]) =>
      [ ...result, { produit, attribute, value } ], acc))(item), []);

console.log(altered);
代码语言:javascript
复制
.as-console-wrapper { top: 0; max-height: 100% !important; }

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64141358

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档