我是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的文档中找到一些东西,但是我不知道怎么做。
发布于 2020-10-01 00:08:01
您可以使用_.flatMap(),方法是为每个对象destructuring produit键,然后将剩余对象的keys/values mapping到一个新对象,其中包括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>
发布于 2020-10-01 00:09:35
您不需要使用lodash来完成此操作。您可以使用对象销毁和缩减轻松完成此操作。
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);.as-console-wrapper { top: 0; max-height: 100% !important; }
https://stackoverflow.com/questions/64141358
复制相似问题