sujon
sujon

Reputation: 367

How to filter array of objects in javascript?

Here is my input :

const data = [
  { group: [{ label: "Can View" }, { label: "Can Create" }] },
  { topgroup: [{ label: "Can View" }, { label: "Can Create" }] },
  { emptyGorup: [] }
];

I am converting array of object to object by using this code

method 1 :

let permissions =
  data &&
  data.reduce((a, b) => {
    const onlyKey = Object.keys(b)[0];
    a[onlyKey] = b[onlyKey].map(i => i.value);
    return a;
  }, {});
//Output : {group:["can view","can create"],topgroup:["can view","can create"],emptygroup:[]}

My question is that I don't want to get object property if Object property is empty []. For example, In my output, I can see object property emptygroup is [].

 {emptygroup:[]}.

My expected output will be if emptygroup is []

//Output : {group:["can view","can create"],topgroup:["can view","can create"]}

How can I do this ?

Upvotes: 0

Views: 64

Answers (3)

Code Maniac
Code Maniac

Reputation: 37755

You can extend your current code. After you get the object you can filter out the key with empty array using filter and build object again from filtered values

let obj = {
  group: ["can view"],
  topgroup: ["can view", "can create"],
  emptygroup: []
}

let finalObj = Object.fromEntries(Object.entries(obj).filter(([key, value]) => Array.isArray(value) && value.length))

console.log(finalObj)

Upvotes: 2

User863
User863

Reputation: 20039

Try checking the length of the array

const permissionData = [
  { group: [{ label: "Can View" }, { label: "Can Create" }] },
  { topgroup: [{ label: "Can View" }, { label: "Can Create" }] },
  { emptyGorup: [] }
];

let permissions =
  permissionData &&
  permissionData.reduce((a, b) => {
    const onlyKey = Object.keys(b)[0];
    if(b[onlyKey].length) {
      a[onlyKey] = b[onlyKey].map(i => i.label);
    }
    return a;
  }, {});
  
console.log(permissions)

Upvotes: 3

bashkovpd
bashkovpd

Reputation: 598

You can add a condition in reduce:

let permissions =
  permissionData &&
  permissionData.reduce((a, b) => {
    const onlyKey = Object.keys(b)[0];
    if (a[onlyKey]) {
      a[onlyKey] = b[onlyKey].map(i => i.value);
    }
    return a;
  }, {});

Upvotes: 1

Related Questions