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

如何用JavaScript根据数组列表匹配对象属性生成目标数组?

问题需求

给定对象数组listArrObj和数组arrList,需要生成一个结构如预期输出所示的数组:遍历arrList中的每个元素,以该元素作为detail字段值,同时收集所有listArrObj里details属性包含该元素的对象的country值,组成country字段的数组。

现有尝试代码
var listArrObj =[
  {id:1, country: "IN", details: ["all", "some"]},
  {id:2, country: "SG", details: ["all", "some"]},
  {id:3, country: "AU", details: ["some"]}
]
var arrList = ["all", "few", "some"]

var result = arrList.map((key) => [
  key,
  listArrObj.filter((x) => x.details && x.details.includes(key)).map((x) => x.country),
]);

console.log(result);
预期输出
[
  {
   "detail": "all",
   "country": ["IN", "SG"]
  },
  {
   "detail": "few",
   "country": []
  },
  {
   "detail": "some",
   "country": ["IN", "AU", "SG"]
  }
]
修正后的代码

现有代码返回的是[key, country数组]的数组结构,和需求的对象结构不符,只需修改map的返回值即可:

var listArrObj =[
  {id:1, country: "IN", details: ["all", "some"]},
  {id:2, country: "SG", details: ["all", "some"]},
  {id:3, country: "AU", details: ["some"]}
]
var arrList = ["all", "few", "some"]

var result = arrList.map((key) => ({
  detail: key,
  country: listArrObj.filter((x) => x.details && x.details.includes(key)).map((x) => x.country),
}));

console.log(result);
代码说明
  • 把原map返回的数组改为返回包含detail和country属性的对象,直接匹配预期结构
  • 原有的filter+map逻辑是正确的:先筛选出details包含当前key的对象,再提取对应的country值组成数组;对于arrList中不存在于任何details的元素(比如few),会自动返回空数组,符合需求

内容的提问来源于stack exchange,提问作者learntocode2468

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 21:46:14