javascript - 如何使用 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 的文档中找到一些东西,但我不知道该怎么做。
解决方案
您可以使用_.flatMap()
, 通过解构每个对象的键produit
,然后将剩余对象的键/值映射到一个新对象,该对象包括键,键作为键,值作为键:produit
attribute
value
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>
推荐阅读
- python - 如何在并行进程(python-asyncio)中将项目附加到列表中?
- php - 我们计算的请求签名与您提供的签名不匹配。在 php 中检查您的 AWS 秘密访问密钥和签名方法
- php - 发布新产品时如何获取 woocommerce 产品的所有详细信息?
- r - 有没有办法从 shinyapp.io 链接找到 R 代码?
- c++ - xcode 13 无法编译某些函数 c++
- python - 使用类中的函数关闭弹出窗口(kivy)
- sql - 有没有办法在忽略 Spring Boot 中的外键检查的同时截断表?
- anylogic - 步行图书馆的资源可用性
- node.js - 为什么我的服务器在尝试安装 SCSS 后停止工作?
- c - 由于使用指向结构的指针的函数,for 循环意外中断