【发布时间】:2018-02-26 09:42:32
【问题描述】:
我正在尝试将相关的 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"
}
]
}
]
【问题讨论】:
-
您希望
"text": "hello world"在第二个对象中吗?还是复制粘贴问题 -
为什么第一个实体没有
text,而第二个实体没有entity? -
不,我得到两个“不同”的对象,它们的
text键相同,我想将它们分组。 -
但是您在实体上拥有的对象(所需的输出)与您开始的不同
-
@Eddie 更新了问题。
标签: javascript json ecmascript-6