我有一个对象数组:
[
{
product: "ABC",
features: [1,2,3]
},
{
product: "CDE",
features: [1,2]
},
{
product: "XYZ",
features: [3,4,5]
}
]
我正在寻找一种方法来帮助打字稿中的Lodash按功能列表将此json分组,并得出以下结果:
[
{
feature: 1,
Products: ["ABC","CDE"]
},
{
feature: 2,
Products: ["ABC","CDE"]
},
{
feature: 3,
Products: ["ABC","XYZ"]
},
{
feature: 4,
Products: ["XYZ"]
},
{
feature: 5,
Products: ["XYZ"]
}
]
答案 0 :(得分:2)
我认为还没有一个可以选择使用的<div class="border">SignUp</div>
功能来满足您的特定情况。所以我写了lodash
是执行您所期望的功能。
fn
function fn(input) {
const allFeatures = input.reduce((features, cur) => {
return _.uniq(_.concat(features, cur.features))
}, [])
return allFeatures.map(feature => ({
feature,
Products: input.filter(prod => prod.features.includes(feature)).map(x => x.product)
}))
}
const input = [
{
product: 'ABC',
features: [1, 2, 3]
},
{
product: 'CDE',
features: [1, 2]
},
{
product: 'XYZ',
features: [3, 4, 5]
}
]
const expected = [
{
feature: 1,
Products: ['ABC', 'CDE']
},
{
feature: 2,
Products: ['ABC', 'CDE']
},
{
feature: 3,
Products: ['ABC', 'XYZ']
},
{
feature: 4,
Products: ['XYZ']
},
{
feature: 5,
Products: ['XYZ']
}
]
console.log('equal expected: ', _.isEqual(fn(input), expected))
或
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
function fn(input) {
const allFeatures = input.reduce((features, cur) => {
return _.uniq(_.concat(features, cur.features))
}, [])
return allFeatures.map(feature => ({
feature,
Products: input.reduce((prods, cur) => cur.features.includes(feature) ? prods.concat(cur.product) : prods, [])
}))
}
const input = [
{
product: 'ABC',
features: [1, 2, 3]
},
{
product: 'CDE',
features: [1, 2]
},
{
product: 'XYZ',
features: [3, 4, 5]
}
]
const expected = [
{
feature: 1,
Products: ['ABC', 'CDE']
},
{
feature: 2,
Products: ['ABC', 'CDE']
},
{
feature: 3,
Products: ['ABC', 'XYZ']
},
{
feature: 4,
Products: ['XYZ']
},
{
feature: 5,
Products: ['XYZ']
}
]
console.log('equal expected: ', _.isEqual(fn(input), expected))
我很想知道是否有更清洁的方法。