1

I have this challenge, where I want to return an array with objects, where the control array has value in the "value" property in its child object.

Besides that, it should also remove objects in control array, where there is no value

const data = [
      {
        'groupName': '1',
        'controls': [
          {'value': ''},
          {'value': ''}
        ]
      },
      {
        'groupName': '2',
        'controls': [
          {'value': ''},
          {'value': '2'}
        ]
      }
    ];

    const result = data.filter(cl => {
      return cl.controls.some(r => {
        return r.value !== '';
      });
    });

    console.log(result);

The result is this

[
  {
    'groupName': '2',
    'controls': [
      {'value': ''},
      {'value': '2'}
    ]
  }
];

but I want it to be this

   [
      {
        'groupName': '2',
        'controls': [
          {'value': '2'}
        ]
      }
    ];

1 Answer 1

2

Use nested filter() instead of some()

const data = [{groupName:"1",controls:[{value:""},{value:""}]},{groupName:"2",controls:[{value:""},{value:"2"}]}];;

const result = data.filter(cl => {
  cl.controls = cl.controls.filter(r => {
    return r.value !== '';
  });
  return cl.controls.length
});

console.log(result);

Note: It mutates the original array. You can use Array.from(data).filter(...) to avoid it

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.