0

I have this array that's returned when a user submits a form:

leaders: [
    {
        email: '[email protected]',
        sites: [
            {
                name: 'Test',
                sitemeta_id: 'xxxxxxxxx',
                _checked: true
            },
            {
                name: 'Test 2',
                sitemeta_id: 'xxxxxxxx',
                _checked: true
            }
        ],
        focused: false,
        _sitesChecked: 1
    },
    {
        email: '[email protected]',
        sites: [
            {
                name: 'Some Name',
                sitemeta_id: 'xxxxx',
                _checked: true
            },
            {
                name: 'Names',
                sitemeta_id: 'xxxxxxxx'
            }
        ],
        focused: false,
        _sitesChecked: 2
    }
]

I'd like to refactor this to send this array in the specific format the backend is expecting, which would only include site names with the value _checked as true, so the site "Names" wouldn't be included, for example:

leaders: [
    {
        email: '[email protected]',
        sites: ['Test', 'Test2']
    },
    {
        email: '[email protected]',
        sites: ['Some Name']
    }
]

What's the best way to achieve this in JS (or AngularJS)?

1 Answer 1

2

You can use .map to transform one array into another, and destructure the arguments to reduce syntax noise:

const leaders = [{email:'[email protected]',sites:[{name:'Test',sitemeta_id:'xxxxxxxxx',_checked:!0},{name:'Test 2',sitemeta_id:'xxxxxxxx'}],focused:!1,_sitesChecked:1},{email:'[email protected]',sites:[{name:'Some Name',sitemeta_id:'xxxxx',_checked:!0},{name:'Names',sitemeta_id:'xxxxxxxx',_checked:!0}],focused:!1,_sitesChecked:2}];

const output = leaders.map(
  ({ email, sites }) => ({
    email,
    sites: sites.reduce(
      (accum, { name, _checked }) => _checked ? [...accum, name] : accum,
      []
    )
  })
);
console.log(output);

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

Comments

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.