简体   繁体   English

如何提取深度嵌套的对象数组并移动到 React Hook state?

[英]How to extract deeply nested array of objects and move to React Hook state?

I have one array of 49 objects in total.我总共有一个包含 49 个对象的数组。 Inside each nested object, there is another nested " children " array.在每个嵌套的 object 中,还有另一个嵌套的“ children ”数组。 And inside this array, there is a value of " text ".在这个数组里面,有一个值“ text ”。

I am trying to map and filter out these values only, to concat/combine the text and move them to my React Hook.我正在尝试 map 并仅过滤掉这些值,以连接/组合文本并将它们移动到我的 React Hook。 This way I am left with only text so I can calculate the reading time based on the amount of textual content.这样我就只剩下文字了,所以我可以根据文字内容的数量来计算阅读时间。

My Hook:我的钩子:

const [textSize, setTextSize] = useState();

4 out of 49 objects example: 49 个对象中的 4 个示例:

0: {_key: 'ade9a24f5cb6', _type: 'block', caption: null, children: Array(1), markDefs: Array(0), …}
1: {_key: '5aa8a2fa2969', _type: 'block', caption: null, children: Array(1), markDefs: Array(0), …}
2: {_key: '602703f9c2b7', _type: 'block', caption: null, children: Array(1), markDefs: Array(0), …}
3: {_key: '211597e8045a', _type: 'block', caption: null, children: Array(1), markDefs: Array(0), …}

Inside one of the "children" array:在“children”数组之一中:

0: {_key: '76f4ec1ed87f', _type: 'span', marks: Array(0), text: 'Lorem ipsum dolor sit amet'}

and from that array, I need the text of each object if that makes sense?从那个数组中,如果有意义的话,我需要每个 object 的文本?

Array has 49 objects => Each object has nested Array (children) => Each children array has value "text". Array 有 49 个对象 => 每个 object 都有嵌套 Array (children) => 每个子数组都有值“text”。

How about something like this?这样的事情怎么样? If I'm understanding your problem correctly..如果我正确理解你的问题..

 let array = [ {_key: 'ade9a24f5cb6', _type: 'block', caption: null, children: [ {_key: '76f4ec1ed87f', _type: 'span', marks: Array(0), text: '1 Lorem ipsum dolor sit amet'}, {_key: '76f4ec1ed87f', _type: 'span', marks: Array(0), text: '2 Lorem ipsum dolor sit amet'} ], markDefs: Array(0) }, {_key: '5aa8a2fa2969', _type: 'block', caption: null, children: [ {_key: '76f4ec1ed87f', _type: 'span', marks: Array(0), text: '3 Lorem ipsum dolor sit amet'} ], markDefs: Array(0) }, {_key: '602703f9c2b7', _type: 'block', caption: null, children: [ {_key: '76f4ec1ed87f', _type: 'span', marks: Array(0), text: '4 Lorem ipsum dolor sit amet'}, {_key: '76f4ec1ed87f', _type: 'span', marks: Array(0), text: '5 Lorem ipsum dolor sit amet'}, {_key: '76f4ec1ed87f', _type: 'span', marks: Array(0), text: '6 Lorem ipsum dolor sit amet'}, ], markDefs: Array(0) }, {_key: '211597e8045a', _type: 'block', caption: null, children: [], markDefs: Array(0) } ] let results = array.map(x => x.children).flat().map(y => y.text); console.log(results);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM