Javascript 将对象数组转换为新对象
下面的代码工作正常,提供了所需的输出,但我想知道是否有更简洁的方法来实现最终结果。具体来说,是否有一种方法可以消除声明Javascript 将对象数组转换为新对象,javascript,Javascript,下面的代码工作正常,提供了所需的输出,但我想知道是否有更简洁的方法来实现最终结果。具体来说,是否有一种方法可以消除声明const consolidated={}?也许Object.assign()有潜力 const forecast = [ { productId: 111, bucket: '2021-05-01', quantity: 3500 }, { productId: 111, bucket: '2021-06-01', quantity: 3600 }, {
const consolidated={}代码>?也许Object.assign()
有潜力
const forecast = [
{ productId: 111, bucket: '2021-05-01', quantity: 3500 },
{ productId: 111, bucket: '2021-06-01', quantity: 3600 },
{ productId: 111, bucket: '2021-07-01', quantity: 4100 },
{ productId: 111, bucket: '2021-08-01', quantity: 4000 },
{ productId: 111, bucket: '2021-09-01', quantity: 3800 }
];
const consolidated = {};
forecast.forEach(o => {
consolidated[o.bucket] = o.quantity
});
console.log('consolidated', consolidated);
输出:
您可以使用对象在一个步骤中完成此操作。fromEntries
:
const consolidated = Object.fromEntries(
forecast.map(o => [o.bucket, o.quantity])
);
但是Object.fromEntries
是一种有点新的方法-过时的浏览器不理解它,所以请确保包含一个polyfill(如果这是一个专业项目,您可能已经在做了)。您可以使用Object.fromEntries
一步完成此操作:
const consolidated = Object.fromEntries(
forecast.map(o => [o.bucket, o.quantity])
);
但是Object.fromEntries
是一种有点新的方法-过时的浏览器不理解它,所以请确保包含一个polyfill(如果这是一个专业项目,您可能已经在这样做了)。使用Array\reduce
const
预测=[{productId:111,桶:“2021-05-01”,数量:3500},{productId:111,桶:“2021-06-01”,数量:3600},{productId:111,桶:“2021-07-01”,数量:4100},{productId:111,桶:“2021-08-01”,数量:4e3},{productId:111,桶:“2021-09-01”,数量:3800}],
res=forecast.reduce(
(res,{bucket,quantity})=>((res[bucket]=数量),res),{}
);
控制台日志(res)代码>使用数组#减少
const
预测=[{productId:111,桶:“2021-05-01”,数量:3500},{productId:111,桶:“2021-06-01”,数量:3600},{productId:111,桶:“2021-07-01”,数量:4100},{productId:111,桶:“2021-08-01”,数量:4e3},{productId:111,桶:“2021-09-01”,数量:3800}],
res=forecast.reduce(
(res,{bucket,quantity})=>((res[bucket]=数量),res),{}
);
控制台日志(res)代码>对于工作代码,您应该要求输入,而不是StackOverflow。请将输出作为文本,而不是文本图片。在这种情况下,您可以使用console.log(JSON.stringify(consolidated,null,2))
获得经过修饰的输出。对于工作代码,您应该要求输入,而不是在StackOverflow中,请将输出作为文本,而不是文本图片。在本例中,您可以使用console.log(JSON.stringify(consolidated,null,2))
获得经过修饰的输出。