使用嵌套数组的对象字段值 javascript 在数组中分组

group by in array using nested array's object field value javascript

我有一个这样的数组

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 下分组。

有什么帮助吗?

你需要return想要的值属性。

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>