-1

I'm new to JavaScript/jQuery and there's probably an easy way to do this, but I'm unable to find the function or syntax I need. Basically, I have a set of objects like this:

{
  "Object1": [
    {
      "Value": "ABC",
      "IsEnabled": true
    },
    {
      "Value": "DEF",
      "IsEnabled": false
    }
  ],
  "Object2": [
    {
      "Value": "GHI",
      "IsEnabled": false
    }
  ]
}

And I want to turn it into a new set of objects based on the "IsEnabled" value equals true.

{
  "Object1": [
    {
      "Value": "ABC",
      "IsEnabled": true
    }
  ]
}

If it's simpler, I would also be OK with not a new object, but the existing object with the "IsEnabled"=false objects removed. Any help is appreciated, thanks.

3
  • 2
    Doesn't the filter() method do what you want?
    – Barmar
    Commented Mar 19, 2021 at 21:06
  • It probably does, but I don't understand the syntax I need to loop through each Object in my set of objects, and filter out the array inside each Object based on IsEnabled. Everything I tried either threw an error or returned undefined. Commented Mar 19, 2021 at 21:09
  • 1
    Please edit your question with the attempts you've made. Commented Mar 19, 2021 at 21:09

2 Answers 2

2

Loop over the properties in the outer object. For each of them, call filter() to get just the enabled objects in the array. If the resulting array is not empty, add it to the result.

const input = {
  "Object1": [
    {
      "Value": "ABC",
      "IsEnabled": true
    },
    {
      "Value": "DEF",
      "IsEnabled": false
    }
  ],
  "Object2": [
    {
      "Value": "GHI",
      "IsEnabled": false
    }
  ]
};

const output = {};

Object.entries(input).forEach(([key, array]) => {
  const new_array = array.filter(el => el.IsEnabled);
  if (new_array.length > 0) {
    output[key] = new_array;
  }
});

console.log(output);

0
1

If you are in for a functional programming pattern, you can for instance use Object.entries, then map and filter on that array of pairs, and finally Object.fromEntries:

let obj = {"Object1": [{"Value": "ABC","IsEnabled": true},{"Value": "DEF","IsEnabled": false}],"Object2": [{"Value": "GHI","IsEnabled": false}]};

let result = Object.fromEntries(
    Object.entries(obj)
          .map(([k, arr]) => [k, arr.filter(o => o.IsEnabled)])
          .filter(([, arr]) => arr.length)
);

console.log(result);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.