简体   繁体   中英

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 ?

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)

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)

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;
  }, {});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM