如何从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 } } })
常见错误原因
你之前没得到预期结果大概率是以下两种情况:
- 遍历过程中直接修改了原数组的对象属性,没有返回全新构造的对象
- 没有正确拿到外层动态的键名(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
相关产品推荐
相关产品推荐

