简体   繁体   English

如何过滤javascript中的对象数组?

[英]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 [].我的问题是,如果 Object 属性为空 [],我不想获取 object 属性。 For example, In my output, I can see object property emptygroup is [].例如,在我的输出中,我可以看到对象属性 emptygroup 是 []。

 {emptygroup:[]}.

My expected output will be if emptygroup is []我的预期输出是如果 emptygroup 是 []

//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:您可以在 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;
  }, {});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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