我有一个这样的数组

data = [
  { name : "sa", attributes : [{skin : "green"},{nose:"good"}]},
  { name : "sa", attributes : [{skin : "red"},{nose:"bad"}]},
  { name : "sa", attributes : [{skin : "green"},{nose:"good"}]},
  { name : "sa", attributes : [{nose:"good}]},
]

所以我想要基于皮肤属性的数组分组.我正在使用这样的下划线库

const attributeType = "skin";
const groupedCollections = _.groupBy(colls, (col) => {
  const data = col.attributes.find((attribute) => {
    const keys = Object.keys(attribute);
    return keys.indexOf(attributeType) > -1 ? true : false
  });
  return data?.value
});

但这使得分组低于undefined.

有什么帮助吗?

推荐答案

你需要返还你想要的财产的价值.

const
    colls = [{ name: "sa", attributes: [{ skin: "green" }, { nose: "good" }] }, { name: "sa", attributes: [{ skin: "red" }, { nose: "bad" }] }, { name: "sa", attributes: [{ skin: "green" }, { nose: "good" }] }, { name: "sa", attributes: [{ nose: "good" }] }],
    attributeType = "skin",
    groupedCollections = _.groupBy(colls, ({ attributes }) =>  attributes
        .find(attribute => attributeType in attribute)
        ?.[attributeType]
    );

console.log(groupedCollections);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

Javascript相关问答推荐

回归函数不会迭代到foreach中的下一个元素

在JavaScript中,如何将请求的回调函数的结果合并到运行的代码中?

不渲染具有HTML参数的React元素

如何按预期聚合SON数据?

使用redux-toolet DelivercThunks刷新访问令牌

当promise 在拒绝处理程序被锁定之前被拒绝时,为什么我们会得到未捕获的错误?

是什么原因导致此Angular 16应用程序中类型错误时属性结果不存在?

如何判断属于多个元素的属性是否具有多个值之一

如何才能拥有在jQuery终端中执行命令的链接?

深嵌套的ng-container元素仍然可以在Angular 布局组件中正确渲染内容吗?

React 17与React 18中的不同setState行为

为什么当我解析一个promise时,输出处于挂起状态?

v—自动完成不显示 Select 列表中的所有项目

无法检测卡片重叠状态的问题

一个实体一刀VS每个实体多刀S

无法避免UV:flat的插值:非法使用保留字"

在不扭曲纹理的情况下在顶点着色器中旋转UV

更改agGRID/Reaction中的单元格格式

Pevent触发material 用户界面数据网格中的自动保存

为什么NULL不能在构造函数的.Prototype中工作