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

如何从对象的tags中生成指定格式的键值对字符串数组

处理JavaScript对象数组生成指定格式字符串数组

给定如下JavaScript对象数组:

const data3 = [
  {
    calculatedPropertyDescription: "where evri_courionsignature_gb is Dispatched",
    category: "red",
    tags: [
      { name: 'LandingPage', value: 'true' },
      { name: 'Country', value: 'GB' },
      { name: 'Carrier', value: 'RoyalMail' },
      { name: 'EventCode', value: 'Dispatched' },
    ]
  },
  {
    calculatedPropertyDescription: "where evgnature_gb is Dispatched",
    category: "red",
    tags: [
      { name: 'LandingPage', value: 'true' },
      { name: 'Country', value: 'USA' },
      { name: 'Carrier', value: 'Evri' },
      { name: 'EventCode', value: 'Dispatched' },
    ]
  },
]

需要将每个对象的tags数组元素转换为name:value格式的字符串,最终生成包含所有这些字符串的一维数组,可以用以下代码实现:

const result = data3.flatMap(item => 
  item.tags.map(tag => `${tag.name}:${tag.value}`)
);

console.log(result);

运行后得到的结果:

[
  'LandingPage:true',
  'Country:GB',
  'Carrier:RoyalMail',
  'EventCode:Dispatched',
  'LandingPage:true',
  'Country:USA',
  'Carrier:Evri',
  'EventCode:Dispatched'
]

如果需要保留原数组的结构,生成每个对象对应处理后的二维数组,把flatMap换成map即可:

const result = data3.map(item => 
  item.tags.map(tag => `${tag.name}:${tag.value}`)
);

console.log(result);

对应的输出:

[
  [
    'LandingPage:true',
    'Country:GB',
    'Carrier:RoyalMail',
    'EventCode:Dispatched'
  ],
  [
    'LandingPage:true',
    'Country:USA',
    'Carrier:Evri',
    'EventCode:Dispatched'
  ]
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 10:12:39