[英]How can I finish transforming this JSON returned from a GraphQL query?
我正在尝试转换从我的GraphQL查询返回的嵌套JSON对象和数组的对象。 通过将我的数据传递给map()函数并使用散布运算符,我可以在大多数情况下对数据进行拼合,但是我无法弄清楚如何更深入地完成工作。
数据源:
// data from GraphQL
var sampledata = {
data: {
allNodeResource: {
edges: [
{
node: {
title: "Sample node 1",
desc: {
description: "Sample description"
},
relationships: {
sin: [
{
name: "Gluttony"
},
{
name: "Greed"
}
]
}
}
},
{
node: {
title: "Sample node 2",
desc: {
description: "Another sample description"
},
relationships: {
sin: [
{
name: "Lust"
},
{
name: "Wrath"
},
{
name: "Envy"
}
]
}
}
}
]
}
}
};
这是我最初的尝试:
const flatten = arr =>
arr.map(({ node: { title, relationships: sin, desc } }) => ({
title,
...desc,
...sin,
}));
const transformedJSON = flatten(sampledata.data.allNodeResource.edges);
这使我大部分了,然后返回此结果(如您所见, description
现在是平坦的,而sin
几乎是平坦的,但不完全是!):
[
{
"title": "Sample node 1",
"description": "Sample description",
"sin": [
{
"name": "Gluttony"
},
{
"name": "Greed"
}
]
},
{
"title": "Sample node 2",
"description": "Another sample description",
"sin": [
{
"name": "Lust"
},
{
"name": "Wrath"
},
{
"name": "Envy"
}
]
}
]
我的最终目标低于目标,但对于我的一生,我不知道该如何到达这里:
[
{
"node": {
"title": "Sample node 1",
"description": "Sample description",
"sin": [
"Gluttony",
"Greed"
]
}
},
{
"node": {
"title": "Sample node 2",
"description": "Another sample description",
"sin": [
"Lust",
"Wrath",
"Envy"
]
}
}
]
我觉得我不知道如何解决这个语法错误,并尝试了多种组合,例如尝试通过另一个map()函数将sin
,但是我似乎无法提出正确的技术(也许这是完全错误的方法。)
任何有关如何推动这一进展的技巧将不胜感激...
这里的Codesandbox: https ://codesandbox.io/s/jovial-jennings-h6smp ? fontsize = 14
const newJSON = transformedJSON.map(json => {
const changed = {...json};
changed.sin = changed.sin.reduce((result, sin) => {
return result.concat(sin.name);
}, []);
return changed;
});
稍微调整您的flatten
功能,您可以像这样使sin对象展平:
const flatten = arr =>
arr.map(({ node: { title, relationships, desc, ...rest } }) => ({
title,
sin: relationships.sin.map(sinObj => sinObj.name),
...desc,
...rest
}));
在此处分叉的CodeSandbox: https ://codesandbox.io/s/hardcore-glitter-f4xhn
您只需要从sin对象中拔出名称即可。 我还消除了将relationships
破坏成sin
原因,因为那导致您最终得到一个看起来像sin: { sin: {}}
的对象sin: { sin: {}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.