这类似于this question,但稍微扭曲一下,数组旁边还有其他对象值,我似乎无法找出获得所需内容的精确语法。
我有这样的事情:
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'}
]
}
]
...我希望将fieldName的所有值都放到自己的数组中,这样我最终得到的结果如下:
someFieldArray = ['one', 'two', 'three', 'four']
几乎每一次尝试都在某个地方窒息。我知道我很接近使用迭代和解构的组合,但似乎无法获得精确的语法和组合正确。我正在使用使用Babel编译的ES2015(6)。任何有关如何完成此任务的帮助表示赞赏!我可以首先将元数据解构为对象,如果这样可以使事情变得更容易({... metadata})。
答案 0 :(得分:3)
在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>');
答案 1 :(得分:1)
由于您要求采用ES6方法,因此该解决方案可能就是您所寻求的。
[].concat(...metadata.map(item => item.controls.map(obj => obj.fieldName)));