gpt4 book ai didi

javascript - 使用高阶函数合并相等的对象

转载 作者:搜寻专家 更新时间:2023-10-30 21:01:41 24 4
gpt4 key购买 nike

如果数组中的值彼此相等,我想“合并”对象。

这是一个例子:

"relations_entities": [
{
"relation": {
"label": string,
"inEntityId": string,
"outEntityId": string,
"proof": [
{
"text": string,
"confidence": number,
}
],
},
"entity": {
"entityId": string,
"label": string,
"text": string,
},
},
{
"relation": {
"label": string,
"inEntityId": string,
"outEntityId": string,
"proof": [
{
"text": string,
"confidence": number,
}
],
},
"entity": {
"entityId": string,
"label": string,
"text": string,
},
},
]

如果 relations_entities[0].relation.labelrelations_entities[0].entity.label 等于 relations_entities[0].relation.label relations_entities[0].entity.label

然后我需要这个对象是:

"relations_entities": [
{
"relation": {
"label": string,
"inEntityId": string,
"outEntityId": string,
"proof": [
{
"text": string,
"confidence": number,
},
{
"text": string,
"confidence": number,
}
],
},
"entity": {
"entityId": string,
"label": string,
"text": string,
},
},
]

两个证明合并。

我尝试使用过滤器实现此行为,但我失去了理智。

也许使用 lodash 库?

有什么想法吗?

最佳答案

看看它:

let relations_entities = [
{
relation: {
label: 'string',
inEntityId: 'string',
outEntityId: 'string',
proof: [
{
text: 'string',
confidence: 'number',
}
],
},
entity: {
entityId: 'string',
label: 'string',
text: 'string',
},
},
{
relation: {
label: 'string',
inEntityId: 'string',
outEntityId: 'string',
proof: [
{
text: 'string',
confidence: 'number',
}
],
},
entity: {
entityId: 'string',
label: 'string',
text: 'string',
},
},
];

let merged = [];

relations_entities.forEach(el => {
let found = false;
if (merged.length > 0) {
merged.forEach(elM => {
if (el.relation.label === elM.relation.label && !found) {
elM.relation.proof = elM.relation.proof.concat(el.relation.proof);
found = true;
}
});
}
if (!found || merged.length === 0) {
merged.push(el);
}
});

console.log(merged);

关于javascript - 使用高阶函数合并相等的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50488465/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com