[英]Getting nested object array values into another array
這類似於這個問題 ,但是有一點曲折,因為在數組旁邊還有其他對象值,而且我似乎還不太清楚找出所需的確切語法。
我有這樣的事情:
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})。
在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.