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

如何从现有对象生成带条件属性的对象数组?

问题描述

给定如下对象:

data = {
  "teste1": "value1",
  "teste2": "value2",
  "teste3": "value3",
  "noquizz": {
    "teste4": "value4",
    "teste5": "value6"
  }
}

期望转换为以下数组结构:

mapped = [
  {id: "teste1", value: "value1"},
  {id: "teste2", value: "value2"},
  {id: "teste3", value: "value3"},
  {id: "noquizz", answers: {
                             "teste4": "value4",
                             "teste5": "value6"
                            }
  }
]

当前实现代码:

const mapped = Object.keys(this.data).map(key => ({id: key, value: this.data[key]}));

需要补充逻辑:当键包含QUIZZ(不区分大小写)时,用answers属性替代value属性。


解决方案

你可以在map的回调函数中加入条件判断,根据键的特征返回对应结构的对象:

方案1:基础条件判断写法

const mapped = Object.keys(this.data).map(key => {
  // 不区分大小写检查键是否包含QUIZZ
  if (key.toLowerCase().includes('quizz')) {
    return { id: key, answers: this.data[key] };
  }
  return { id: key, value: this.data[key] };
});

方案2:严格区分大小写版本

如果只需要匹配包含大写QUIZZ的键,去掉toLowerCase()即可:

const mapped = Object.keys(this.data).map(key => {
  if (key.includes('QUIZZ')) {
    return { id: key, answers: this.data[key] };
  }
  return { id: key, value: this.data[key] };
});

方案3:简化的三元表达式写法

用对象展开和三元表达式压缩代码:

const mapped = Object.keys(this.data).map(key => ({
  id: key,
  ...(key.toLowerCase().includes('quizz') 
    ? { answers: this.data[key] } 
    : { value: this.data[key] })
}));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 17:30:11