1

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

1
  • Do you want only unique fieldName values, or all values? Commented Apr 4, 2016 at 14:17

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, fast, and much less complicated then what I was trying. Thanks!
2

Since you're asking for an ES6 approach, this solution might be what you're looking for.

[].concat(...metadata.map(item => item.controls.map(obj => obj.fieldName)));

1 Comment

Changed this to the accepted answer since I did mention I am using ES6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.