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

如何从JavaScript对象数组中提取每个对象的指定属性并保留外层键

你可以通过以下方式使用map实现需求:

const arr1 = [
  {person: {isPresent: true, isInsured: true, value:20}},
  {status: {isPresent: true, isInsured: true, value:20}},
]

const res = arr1.map(item => {
  // 获取当前项的唯一一级键名
  const firstKey = Object.keys(item)[0]
  // 构造符合要求的新对象
  return {
    [firstKey]: {
      value: item[firstKey].value
    }
  }
})

常见错误原因

你之前没得到预期结果大概率是以下两种情况:

  1. 遍历过程中直接修改了原数组的对象属性,没有返回全新构造的对象
  2. 没有正确拿到外层动态的键名(person、status),导致丢失了外层的键结构,或者嵌套层级写错

如果你的一级键名是固定的只有person和status,也可以用更直白的写法:

const res = arr1.map(item => {
  if (item.person) return { person: { value: item.person.value } }
  if (item.status) return { status: { value: item.status.value } }
  return item
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 02:06:10