[英]Getting nested object array values into another array
This is similar to this question , but with a slight twist in that there other object values beside the arrays and I can't quite seem to figure out the precise syntax to get what I need. 这类似于这个问题 ,但是有一点曲折,因为在数组旁边还有其他对象值,而且我似乎还不太清楚找出所需的确切语法。
I have something like this: 我有这样的事情:
const metadata = [
{
stepName: 'Step one',
controls: [
{fieldName: 'one', label: 'Field One', type: 'input'},
{fieldName: 'two', label: 'Field Two', type: 'multiline'}
]
},
{
stepName: 'Step two',
controls: [
{fieldName: 'three', label: 'Field Three', type: 'input'},
{fieldName: 'four', label: 'Field Four', type: 'multiline'}
]
}
]
...and I want to get all the values for fieldName into there own array so that I end up with something like: ...而且我想将fieldName的所有值放入自己的数组中,以便得到类似以下的结果:
someFieldArray = ['one', 'two', 'three', 'four']
Just about every attempt I have made chokes somewhere. 几乎我在某处做过窒息的尝试。 I know I am close using a combination of iteration and destructuring, but can't quite seem to get the precise syntax and combination correct. 我知道我已经接近使用迭代和解构的组合,但是似乎无法正确获得准确的语法和组合。 I am using ES2015 (6) transpiled using Babel. 我正在使用通过Babel转译的ES2015(6)。 Any help on how to get this done is appreciated! 感谢您提供有关如何完成此操作的帮助! I can destructure metadata into an object first if that will make things easier ({...metadata}). 我可以先将元数据分解为一个对象,如果这样做会使事情变得更容易({... metadata})。
In ES5, you could write this. 在ES5中,您可以编写此代码。
var metadata = [{ stepName: 'Step one', controls: [{ fieldName: 'one', label: 'Field One', type: 'input' }, { fieldName: 'two', label: 'Field Two', type: 'multiline' }] }, { stepName: 'Step two', controls: [{ fieldName: 'three', label: 'Field Three', type: 'input' }, { fieldName: 'four', label: 'Field Four', type: 'multiline' }] }], result = metadata.reduce(function (r, a) { return r.concat(a.controls.map(function (b) { return b.fieldName; })); }, []); document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
由于您要使用ES6方法,因此可能需要此解决方案。
[].concat(...metadata.map(item => item.controls.map(obj => obj.fieldName)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.