寻找问题的解决方案:
需要合并以下数组,以便最终输出只有一行对应于类别和子类别的每个唯一组合,其余字段(主题和个人)则合并为一个数组:
输入:
[
{
"category":"cat2",
"subcategory":"b",
"personal":[
"inclsn2"
],
"topic":[
"topic1",
"topic3"
]
},
{
"category":"cat1",
"subcategory":"a",
"personal":[
"inclsn2"
],
"topic":[
"topic4"
]
},
{
"category":"cat2",
"subcategory":"b",
"personal":[
"inclsn2"
],
"topic":[
"topic5",
"topic2"
]
},
{
"category":"cat2",
"subcategory":"b",
"personal":[
"inclsn2"
],
"topic":[
"topic1",
"topic2"
]
},
{
"category":"cat2",
"subcategory":"b",
"personal":[
"inclsn2"
],
"topic":[
"topic1",
"topic2"
]
},
{
"category":"cat1",
"subcategory":"a",
"personal":[
"inclsn2"
],
"topic":[
"topic1",
"topic2"
]
},
{
"category":"cat1",
"subcategory":"a",
"personal":[
"inclsn2"
],
"topic":[
"topic1",
"topic2"
]
},
{
"category":"cat3",
"subcategory":"c",
"personal":[
"inclsn3"
],
"topic":[
"topic1",
"topic2"
]
},
{
"category":"cat1",
"subcategory":"a",
"personal":[
"inclsn2"
],
"topic":[
"topic1",
"topic2"
]
},
{
"category":"cat1",
"subcategory":"a",
"personal":null,
"topic":[
"topic6"
]
}
]
预期输出:
[{"category": "cat2", "subcategory": "b", "personal": ["inclsn2"], "topic": ["topic2","topic5","topic4","topic1"]},
{"category": "cat1", "subcategory": "a", "personal": ["inclsn2"], "topic": ["topic6","topic2","topic4","topic1"]},
{"category": "cat3", "subcategory": "c", "personal": ["inclsn3"], "topic": ["topic1","topic2"]}]
对此将提供任何帮助。
谢谢
答案 0 :(得分:0)
您的问题的一种解决方案是使用之前不了解类别/子类别组合的条件来过滤数组。您可以使用其键是类别/子类别的组合(例如,与某些定界符串联)的对象,然后查看该对象是否具有给定的键。
您可以使用以下方法做到这一点:
const input = [] // your array here
const d = '\t';
const merge = (a, c = {}) => a.filter((e, f, k) =>
(k = e.category + d + e.subcategory, f = c[k], c[k] = 1, !f));
console.log(merge(input));
请确保将d
设置为永远不会属于真实类别或子类别名称的字符串-这是一个制表符,但您可以将其设置为其他任何字符。
阵列的输出:
[ { category: 'cat2',
subcategory: 'b',
personal: [ 'inclsn2' ],
topic: [ 'topic1', 'topic3' ] },
{ category: 'cat1',
subcategory: 'a',
personal: [ 'inclsn2' ],
topic: [ 'topic4' ] },
{ category: 'cat3',
subcategory: 'c',
personal: [ 'inclsn3' ],
topic: [ 'topic1', 'topic2' ] } ]
如果您使用的是Lodash,则可以进一步简化merge()
函数:
const _ = require('lodash');
const d = '\t';
const merge = a => _.uniqBy(a, e => e.category + d + e.subcategory);
console.log(merge(input));