Home > OS >  How to check if specific values of Object items in Array
How to check if specific values of Object items in Array

Time:10-06

My goal: I want to modify this Array (See; Current Array with Objects) to only main properties where one or more (items) is greater than 0. In this example, the current Array should be modified by removing all object named: tags and sale_status from the Array, since there are no items is higher than 0 with count. So you only keep the Object over quotation_status.

How can I handle this the right way? I've tried various ways of looping, but can't figure it out.

Current Array with Objects

[{
    "id": "tags",
    "label": "Tags",
    "items": [{
        "key": 2,
        "count": 0
    }, {
        "key": 1,
        "count": 0
    }, {
        "key": 3,
        "count": 0
    }]
}, {
    "id": "sale_status",
    "label": "Status",
    "items": [{
        "key": "completed",
        "count": 0
    }, {
        "key": "processing",
        "count": 0
    }, {
        "key": "on-hold",
        "count": 0
    }]
}, {
    "id": "quotation_status",
    "label": "Status",
    "items": [{
        "key": "concept",
        "count": 1
    }]
}]

Desired output:

[{
    "id": "quotation_status",
    "label": "Status",
    "items": [{
        "key": "concept",
        "count": 1
    }]
}]

Current Script

function activeFilters() {
  let test = test1.value
  let filters = store.getters[test].filters

  const result = filters.filter((o) => o.items.some((obj) => obj.count));
  return result;
};

CodePudding user response:

You can use filter and some to get the desired result

arr.filter((o) => o.items.some((obj) => obj.count))

const arr = [
  {
    id: "tags",
    label: "Tags",
    items: [
      {
        key: 2,
        count: 0,
      },
      {
        key: 1,
        count: 0,
      },
      {
        key: 3,
        count: 0,
      },
    ],
  },
  {
    id: "sale_status",
    label: "Status",
    items: [
      {
        key: "completed",
        count: 0,
      },
      {
        key: "processing",
        count: 0,
      },
      {
        key: "on-hold",
        count: 0,
      },
    ],
  },
  {
    id: "quotation_status",
    label: "Status",
    items: [
      {
        key: "concept",
        count: 1,
      },
    ],
  },
];

const result = arr.filter((o) => o.items.some((obj) => obj.count));
console.log(result);

  • Related