使用嵌套数组的对象字段值javascript对数组进行分组

发布于 2025-01-10 04:28:28 字数 685 浏览 5 评论 0原文

我有一个这样的数组

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

,但这正在未定义下进行分组。

有什么帮助吗?

I have an array like this

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}]},
]

so i want the grouping of array based on skin attribute. I am using _ underscore library like this

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

but this is making grouping under undefined.

Any help?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

自此以后,行同陌路 2025-01-17 04:28:28

您需要返回所需属性的值。

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>

You need to return the value of the wanted property.

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>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文