gpt4 book ai didi

Javascript - 将 javascript 对象数组转换为排序的键/值 javascript 对象

转载 作者:行者123 更新时间:2023-12-01 00:38:38 24 4
gpt4 key购买 nike

我有一个不定大小的 JavaScript 对象数组:

var arr = [      
{
"Entities":
[
{
"BeginOffset": 28,
"EndOffset": 35,
"Score": 0.9945663213729858,
"Text": "Tunisie",
"Type": "LOCATION"
},
{
"BeginOffset": 60,
"EndOffset": 71,
"Score": 0.8412493228912354,
"Text": "Al HuffPost",
"Type": "PERSON"
},
{
"BeginOffset": 60,
"EndOffset": 71,
"Score": 0.9412493228912354,
"Text": "trump",
"Type": "PERSON"
}
],
"File": "article1.com"
},
{
"Entities":
[
{
"BeginOffset": 28,
"EndOffset": 35,
"Score": 0.9945663213729858,
"Text": "france",
"Type": "LOCATION"
},
{
"BeginOffset": 60,
"EndOffset": 71,
"Score": 0.7412493228912354,
"Text": "john locke",
"Type": "PERSON"
},
{
"BeginOffset": 60,
"EndOffset": 71,
"Score": 0.9412493228912354,
"Text": "sawyer",
"Type": "PERSON"
}
],
"File": "anotherarticle.com"
},
{
//and so on ...
}
]

如何将其转换为键/值 Javascript 对象,其中每个文件提供与其关联的人员数组,而此数据仅对 type="person"和分数 > 0.8 进行过滤,并且在数组内进行排序从最高分数开始(当实体超过 1 人时)。

例如,上面的示例应输出:

var finalObject =    {
"article1.com": ["trump", "Al HuffPost"],//tunisisa not here because entity is a LOCATION
"anotherarticle.com": ["sawyer"] //john locke not here because score <0.8
}

我尝试以各种方式减少、映射和过滤,但总是失败。

最佳答案

下面的代码将通过将输入数组减少为对象、过滤掉不需要的实体、根据分数反向排序以及将剩余实体映射到其 Text 属性来创建请求的输出:

const result = arr.reduce((a, {Entities, File}) => {
a[File] = Entities
.filter(({Type, Score}) => Type === 'PERSON' && Score > 0.8)
.sort((a, b) => b.Score - a.Score)
.map(({Text}) => Text);
return a;
}, {});
<小时/>

完整片段:

const arr = [{
"Entities": [{
"BeginOffset": 28,
"EndOffset": 35,
"Score": 0.9945663213729858,
"Text": "Tunisie",
"Type": "LOCATION"
},
{
"BeginOffset": 60,
"EndOffset": 71,
"Score": 0.8412493228912354,
"Text": "Al HuffPost",
"Type": "PERSON"
},
{
"BeginOffset": 60,
"EndOffset": 71,
"Score": 0.9412493228912354,
"Text": "trump",
"Type": "PERSON"
}
],
"File": "article1.com"
},
{
"Entities": [{
"BeginOffset": 28,
"EndOffset": 35,
"Score": 0.9945663213729858,
"Text": "france",
"Type": "LOCATION"
},
{
"BeginOffset": 60,
"EndOffset": 71,
"Score": 0.7412493228912354,
"Text": "john locke",
"Type": "PERSON"
},
{
"BeginOffset": 60,
"EndOffset": 71,
"Score": 0.9412493228912354,
"Text": "sawyer",
"Type": "PERSON"
}
],
"File": "anotherarticle.com"
}
];

const result = arr.reduce((a, {Entities, File}) => {
a[File] = Entities
.filter(({Type, Score}) => Type === 'PERSON' && Score > 0.8)
.sort((a, b) => b.Score - a.Score)
.map(({Text}) => Text);
return a;
}, {});

console.log(result);

关于Javascript - 将 javascript 对象数组转换为排序的键/值 javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57887282/

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