Skip to content Skip to sidebar Skip to footer

Sort And Filter An Object That Has Numbers In Its Property Names

I am trying to filter out items that has the mode set to null, however, after adding this filter, all items disappear, even if they do not have the mode prop at null. const filtere

Solution 1:

Assuming that botConfig data is object with numbers as properties:

const botConfigs = {
  2: { mode: null, botId: "10", status: "ACTIVE", },
  1: { mode: "A", botId: "20", status: "ACTIVE", },
  3: { mode: "C", botId: "15", status: "STOPPED", },
};

And you want to sort by (number) properties and then filter on properties of values. So, this is how your filters functions might look like:

filterConfigsByBot = (key) => {
  return botConfigs[key].botId !== "0"; // assuming botConfigs is available in scope
};

filterConfigsByStatus = (key) => {
  return botConfigs[key].status !== "STOPPED";
};

Also, remember to map keys to values of botConfigs at the end (if needed):

const filteredAndSortedBotConfigs = Object.keys(botConfigs)
    .sort((a, b) =>parseInt(a, 10) - parseInt(b, 10))
    .filter(this.filterConfigsByBot)
    .filter(this.filterConfigsByStatus)
    .filter((key) => botConfigs[key].mode !== null) // to filter out items that has the `mode` set to `null`
    .map((key) => botConfigs[key]);

PS: You can combine the three filters into a single filter callback.

Edit:

Simplified version using a reduce:

const filteredAndSortedBotConfigs = Object.keys(botConfigs)
    .sort((a, b) =>parseInt(a, 10) - parseInt(b, 10))
    .reduce((acc, curr) => {
    if (
        botConfigs[curr].botId !== "0" &&
        botConfigs[curr].status !== "STOPPED" &&
        botConfigs[curr].mode !== null
    ) {
        acc.push(botConfigs[curr]); // pushing values, not keys
    }
    return acc;
    }, []);

Post a Comment for "Sort And Filter An Object That Has Numbers In Its Property Names"