从具有嵌套字段的对象数组创建对象数组 JavaScript/es6
我正在处理具有嵌套属性的对象数组,有没有办法编写递归函数来实现下面提到的输出
const firstArray = [
{
groupId: '1',
childRows: [
{
groupId: '1a',
childRows: ['abc', 'def'],
},
{
groupId: '1b',
childRows: ['pqr', 'xyz'],
},
],
},
{
groupId: '2',
childRows: [
{
groupId: '2a',
childRows: ['abz', 'dxy'],
},
{
groupId: '2b',
childRows: ['egh', 'mno'],
},
],
},
];
如何在 es6 中编写函数以便返回以下输出
[
{ groupId: '1', childRows: ['abc', 'def', 'pqr', 'xyz'] },
{ groupId: '1a', childRows: ['abc', 'def'] },
{ groupId: '1b', childRows: ['pqr', 'xyz'] },
{ groupId: '2', childRows: ['abz', 'dxy', 'egh', 'mno'] },
{ groupId: '2a', childRows: ['abz', 'dxy'] },
{ groupId: '2b', childRows: ['egh', 'mno'] },
];
I am working on an array of objects which has nested attributes, Is there any way to write a recursive function to achieve below output mentioned
const firstArray = [
{
groupId: '1',
childRows: [
{
groupId: '1a',
childRows: ['abc', 'def'],
},
{
groupId: '1b',
childRows: ['pqr', 'xyz'],
},
],
},
{
groupId: '2',
childRows: [
{
groupId: '2a',
childRows: ['abz', 'dxy'],
},
{
groupId: '2b',
childRows: ['egh', 'mno'],
},
],
},
];
How to write a function in es6 such that below output is returned
[
{ groupId: '1', childRows: ['abc', 'def', 'pqr', 'xyz'] },
{ groupId: '1a', childRows: ['abc', 'def'] },
{ groupId: '1b', childRows: ['pqr', 'xyz'] },
{ groupId: '2', childRows: ['abz', 'dxy', 'egh', 'mno'] },
{ groupId: '2a', childRows: ['abz', 'dxy'] },
{ groupId: '2b', childRows: ['egh', 'mno'] },
];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我找到了解决方案。我试图用代码中的注释来解释你
没有注释的函数:
I found a solution. I tried to explain you with comments in the code
Function without comments:
我想出了这个递归函数。输出对象按预期顺序排列。
然后您调用该函数。
这是输出。
编辑:感谢 J. Villasmil,我看到我们可以使用
array1.push(...array2)
优化array1 = array1.concat(array2)
。我所以更新了我的答案。I came up with this recursive function. The output objects are in the intended order.
You then call the function.
Here is the output.
Edit : Thanks to J. Villasmil, I saw we can optimize
array1 = array1.concat(array2)
witharray1.push(...array2)
. I so updated my answer.一个很好的说法是,
childRows
属性包含字符串或对象,childRowsIn
函数返回 childRows 的字符串,而childRowsIn
childRows 的对象A nice way to say this is that the
childRows
prop contains either strings or objects, and thechildRowsIn
function returns the childRows's strings and thechildRowsIn
the childRows's objects使用
flatMap
、concat
和destructuring
可以简化为Using
flatMap
,concat
anddestructuring
can simplify as