如何将标签添加到 javascript 中的对象值

How to add a lable to an object value in javascript

我有一个按索引分组的对象数组,我想重组并向响应添加标签。

这是我的原始数组:

let cars = [{'make': 'audi', 'model': 'RS3', 'transmition': 'automatic'}, {'make': 'audi', 'model': 'RS7', 'transmition': 'dual-clutch'}, {'make': 'bmw', 'model': '325is', 'transmition': 'manual'}, {'make': 'bmw', 'model': 'M2', 'transmition': 'dual-clutch'}]

这里是通过 make 对数组进行分组的源代码:

var groupedByMake = _.groupBy(
          cars,
          "make"
        );

响应如下所示:

{
  'audi':[{'model': 'RS3', 'transmition': 'automatic'}, {'model': 'RS7', 'transmition': 'dual-clutch'}],
  'bmw':[{'model': '325is', 'transmition': 'manual'}, {'model': 'M2', 'transmition': 'dual-clutch'}]
}

我想要的结果应该是这样的:

[{
  'make': 'audi',
   'types': [{'model': 'RS3', 'transmition': 'automatic'}, {'model': 'RS7', 'transmition': 'dual-clutch'}]
  },{
  'make': 'bmw',
  'types': [{'model': '325is', 'transmition': 'manual'}, {'model': 'M2', 'transmition': 'dual-clutch'}]
}]

使用JavaScript可以实现吗?如果是这样,我可以获得帮助以完成此任务。

const cars = [{'make': 'audi', 'model': 'RS3', 'transmition': 'automatic'}, {'make': 'audi', 'model': 'RS7', 'transmition': 'dual-clutch'}, {'make': 'bmw', 'model': '325is', 'transmition': 'manual'}, {'make': 'bmw', 'model': 'M2', 'transmition': 'dual-clutch'}];
const groupBy = (array, key) => {
  return array.reduce((acc, item) => {
    const keyValue = item[key];
    const existingGroup = acc.find((group) => group.key === keyValue);
    if (existingGroup) {
      existingGroup.items.push(item);
    } else {
      // remove make from item
      const { make, ...rest } = item;
      acc.push({ key: keyValue, items: [rest] });
    }
    return acc;
  }, []);
}


console.log(JSON.stringify(groupBy(cars, 'make'), null, 2));

您可以使用 array.reduce 将一个数组转换为另一个数组,并控制您是 return 新元素还是在现有元素中累加值 (prev):

let cars = [{'make': 'audi', 'model': 'RS3', 'transmition': 'automatic'}, {'make': 'audi', 'model': 'RS7', 'transmition': 'dual-clutch'}, {'make': 'bmw', 'model': '325is', 'transmition': 'manual'}, {'make': 'bmw', 'model': 'M2', 'transmition': 'dual-clutch'}];

let output = cars.reduce((acc, cur) => {
    let {make, ...obj} = cur;    
    let prev = acc.find(x => x.make === make);
    if(!prev) {
      acc.push({make,types:[obj]})
    } else {
      prev.types.push(obj);
    }
    return acc;
}, []);

console.log(output);

如果你想保留你的 groupby as-is(使用 lodash):

  // Result from lodash
var groupedByMake = {
  'audi':[{'model': 'RS3', 'transmition': 'automatic'}, {'model': 'RS7', 'transmition': 'dual-clutch'}],
  'bmw':[{'model': '325is', 'transmition': 'manual'}, {'model': 'M2', 'transmition': 'dual-clutch'}]
}

const result = Object.keys(groupedByMake).map(make => ({make, types: groupedByMake [make]}));

console.log(result);