简体   繁体   中英

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:

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. 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}).

In ES5, you could write this.

 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)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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