使用JavaScript过滤对象数组时如何展开嵌套对象属性到外层
数组嵌套字段摊平导出CSV解决方案
你不需要使用pop/splice这类方法,只需要在原有过滤逻辑的基础上增加嵌套对象的合并逻辑即可,这里提供两种可选方案:
方案1:按需保留嵌套字段(更灵活)
步骤1:调整保留字段配置
将includesArray中原来的Endereco替换为你实际需要从Endereco中提取的字段:
includesArray: ["Cpf", "Nascimento", "Sexo", "Id", "Nome", "Ativo", "Criacao", "UltimaAlteracao", "Email", "Observacoes", "Cep", "Logradouro", "Numero", "Complemento", "Bairro", "Estado", "Cidade"]
步骤2:修改过滤逻辑
遍历到Endereco嵌套对象时,单独提取其内部匹配的字段放到外层:
this.newArray = [] for (const item of this.oldArray) { let tempObject = {}; for (const [key, value] of Object.entries(item)) { // 处理外层普通字段 if (key !== 'Endereco' && this.includesArray.includes(key)) { tempObject[key] = value; } // 处理Endereco嵌套字段 if (key === 'Endereco' && typeof value === 'object' && value !== null) { for (const [subKey, subValue] of Object.entries(value)) { if (this.includesArray.includes(subKey)) { tempObject[subKey] = subValue; } } } } this.newArray.push(tempObject); }
方案2:不修改原有配置,全量摊平Endereco
如果你不需要筛选Endereco内部字段,只想把所有属性都放到外层,可以在原有逻辑基础上增加合并和删除操作:
for (const [key] of Object.entries(this.oldArray)) { let tempObject = {}; // 原有过滤逻辑不变 for (const [keys, values] of Object.entries(this.oldArray[key])) { if (this.includesArray.includes(keys)) { tempObject[keys] = values; } } // 额外处理Endereco嵌套 if (tempObject.Endereco) { // 把Endereco的所有属性合并到外层对象 Object.assign(tempObject, tempObject.Endereco); // 删除嵌套的Endereco字段 delete tempObject.Endereco; } this.newArray[key] = tempObject; }
内容的提问来源于stack exchange,提问作者Veterano
相关产品推荐
相关产品推荐

