You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过reduce方法将数组转换为对象数组且不使用let声明

解决方案

你可以直接使用Array.prototype.flatMap()实现需求,该方法会对每个元素执行映射后自动将返回的子数组扁平化一层,完美适配你每个原数组元素需要生成2个对象的场景,全程不需要额外的可变变量:

适配你示例输出的代码:

const strArr = ["Some", "Thing"];
const result = strArr.flatMap(item => [
  { first_key: item },
  { second_key: item }
]);

适配你现有业务逻辑(title_contains/body_contains)的代码:

const numeros = ["some", 'thing'];
const arr = numeros.flatMap(valor => [
  { title_contains: valor },
  { body_contains: valor }
]);

console.log(arr);

兼容低版本环境的备选方案

如果运行环境不支持flatMap,可以使用map+flat组合,或者reduce实现:

  • map+flat方案
const result = strArr.map(item => [
  { first_key: item },
  { second_key: item }
]).flat();
  • reduce方案
const result = strArr.reduce((acc, item) => {
  acc.push({ first_key: item }, { second_key: item });
  return acc;
}, []);

内容的提问来源于stack exchange,提问作者Nilton Schumacher F

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 05:36:04