按属性分组对象,提取分组结果的子项中的其他属性

时间:2017-11-02 14:27:20

标签: javascript lodash

在我们的应用中,我们从搜索输入中获得了自动提示。返回的数组对应于此模型。

AutoSuggest[] = 
[
    {category: "CAR", type: "COMMON", suggests: ['ford', 'jeep']},
    {category: "TRAVEL", type: "SHORT", suggests: ['tokyo', 'paris', 'london']},
    {category: "TRAVEL", type: "LONG", suggests: ['costa rica', 'greenland']}}
]

我们希望获得合并类别的结果,但保持值和类型分开为两个不同的数组条目。它看起来像这样:

[
    {
        category: "CAR",
        values: [
            { type: "COMMON", suggests: ['ford', 'jeep'] }
        ]
    },
    {
        category: 'TRAVEL',
        values: [
            { type: "SHORT", suggests: ['tokyo', 'paris', 'london'] },
            { TYPE: "LONG", suggests: ['costa rica', 'greenland'] }
        ]
    }
]

尝试使用lodash groupBy,我们只是将我们的建议放入CAR和TRAVEL对象中。但它不符合我们的需要,因为我们需要做一些“提取”原始对象的一部分。

3 个答案:

答案 0 :(得分:2)

您可以使用哈希表将组分组到相同的类别中。

var data = [{ category: "CAR", type: "COMMON", suggests: ['ford', 'jeep'] }, { category: "TRAVEL", type: "SHORT", suggests: ['tokyo', 'paris', 'london'] }, { category: "TRAVEL", type: "LONG", suggests: ['costa rica', 'greenland'] }],
    hash = Object.create(null),
    grouped = [];

data.forEach(function (o) {
    if (!hash[o.category]) {
        hash[o.category] = { category: o.category, values: [] };
        grouped.push(hash[o.category]);
    }
    hash[o.category].values.push({ type: o.type, suggests: o.suggests });
});

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:2)

因为您使用的是 lodash 你可以做点什么

const data = [
  {category: "CAR", type: "COMMON", suggests: ['ford', 'jeep']},
  {category: "TRAVEL", type: "SHORT", suggests: ['tokyo', 'paris', 'london']},
  {category: "TRAVEL", type: "LONG", suggests: ['costa rica', 'greenland']}
]
const grouped = _.chain(data).groupBy('category').map((values,category)=> ({category,values})).value()

console.log(grouped)

哪会返回所需的结果。

答案 2 :(得分:1)

可以使用ES6 AutoSuggest anb Array.prototype.reduce方法从Array.prototype.filter初始数据数组中获取结果:

let result = AutoSuggest.reduce((acc, i) => {
  const value = { type: i.type, suggests: i.suggests };
  const found = acc.find(j => j.category === i.category);
  if(found) {
    found.values.push(value);
  }
  else {
    acc.push({ category: i.category, values: [ value ] });
  }
  return acc;
}, []);