gpt4 book ai didi

javascript - 无法减少数组中相关的 JavaScript 对象

转载 作者:行者123 更新时间:2023-11-28 14:38:39 25 4
gpt4 key购买 nike

我正在尝试按键将相关的 JavaScript 对象分组到数组中。

但是,我陷入了困境。

我有一个像这样的 JavaScript 对象数组:

[
{
"text": "hello world",
"startPos": 0,
"endPos": 12,
"value": "hello world",
"entity": "Greeting"
},
{
"text": "hello world",
"startPos": 0,
"endPos": 6,
"value": "hello",
"entity": "Greeting"
}
]

我编写了以下代码,但我被卡住了。

a = [
{
"text": "hello world",
"startPos": 0,
"endPos": 12,
"value": "hello world",
"entity": "Greeting"
},
{
"text": "hello world",
"startPos": 0,
"endPos": 6,
"value": "hello",
"entity": "Greeting"
}
]

let result = a.reduce((acc, d) => {
const found = acc.find(a => a.text == d.text);
const entitiesArray = {
startPos: d.startPos,
endPos: d.endPos,
entity: d.entity
};
if (found) {
found.entities.push(entitiesArray);
} else {
acc.push({});
}
return acc;
}, []);

console.log(JSON.stringify(result, undefined, 4));

JavaScript 对象根据“text” 键重复。我想根据 "text" 键将上述数组分组为一个对象。

类似这样的事情:

[
{
"text": "hello world",
"entities": [
{
"startPos": 0,
"endPos": 12,
"value": "hello world",
"entity": "Greeting"
},
{
"startPos": 0,
"endPos": 6,
"value": "hello",
"entity": "Greeting"
}
]
}
]

最佳答案

found 为 false 时,您错过了将带有 text 的对象添加到数组中。因此,在接下来的迭代中,它无法找到比较文本的对象

此外,如果您的 IDE 和引擎支持新的 ES 提案,您可以使用 Rest/Spread Properties

const a = [
{
"text": "hello world",
"startPos": 0,
"endPos": 12,
"value": "hello world",
"entity": "Greeting"
},
{
"text": "hello world",
"startPos": 0,
"endPos": 6,
"value": "hello",
"entity": "Greeting"
}
]

let result = a.reduce((acc, d) => {
const found = acc.find(a => a.text == d.text);

const { text, ...entitiesArray } = { ...d }; // <- Rest/Spread properties

found ? found.entities.push(entitiesArray)
: acc.push({ text: d.text, entities: [entitiesArray]})

return acc;
}, []);

console.log(result);

关于javascript - 无法减少数组中相关的 JavaScript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48985409/

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