通过替换在另一个对象中找到的属性名称来创建新对象

问题描述 投票:1回答:4

因此,关于如何遍历对象并简单地更改属性名称,有很多问题,但是我要解决的问题有些棘手,将不胜感激。

基本上,我想制作一个像这样的对象:

{
   home_number: '1234',
   customer: {
     name: {
       last_name: 'Smith',
     },
   },
};

变成这个

{
   home_number: '1234',
   individual: {
     name: {
       lastName: 'Smith',
     },
   },
};

此刻,我的功能如下

function restructure(obj) {
  let newObj = {};
  const newKeys = {
    fed_tax_id: 'federalTaxId',
    company_structure: 'companyStructure',
    home_number: 'homeNumber',
    customer: 'individual',
    first_name: 'firstName',
    last_name: 'lastName',
  }
}
  for(let key in obj){
    if (typeof obj[key] === 'object') {
      restructure(obj[key])
    }
    if(Object.hasOwnProperty.call(newKeys, key)){
      let newProperty = newKeys[key]
      newObj[newProperty] = obj[key]
    }
    if(!Object.hasOwnProperty.call(newKeys, key)){
      newObj[key] = obj[key]
    }
return newObj;
  }

此刻我正在苦苦挣扎的一件事是删除需要更改的键(我创建了newKeys对象,以显示需要更改的键以及需要更改的键的方式。 )。即在这种情况下,当客户更改为个人时,也会将“ last_name”更改为“ lastName”。

通过我目前的功能,该对象以如下方式返回:

{ homeNumber: '1234' }

谢谢:)如果已经问过这个问题,请让我知道,但是在整个地方搜索之后,我找不到一个足够接近这个问题的问题。

javascript object recursion
4个回答
0
投票

由于restructure返回了新对象,因此您需要分配递归调用restructure的结果,否则它将不被使用,这就是当前代码中发生的事情。

但是映射条目数组可能会更容易-将条目中的键替换为对象上的关联值if该对象具有该键,然后将条目转换为带有[ C0]:

Object.fromEntries

请记住,const newKeys = { fed_tax_id: 'federalTaxId', company_structure: 'companyStructure', home_number: 'homeNumber', customer: 'individual', first_name: 'firstName', last_name: 'lastName', }; const restructure = obj => Object.fromEntries( Object.entries(obj).map( ([key, val]) => [ newKeys[key] || key, typeof val === 'object' && val !== null ? restructure(val) : val ] ) ); console.log(restructure({ home_number: '1234', customer: { name: { last_name: 'Smith', }, }, }));给出了typeof null,因此您需要在递归重组之前检查object(如上面的代码所述,否则可能偶尔会出错)。>>


0
投票

您可以使用null从对象中删除属性。


0
投票

您只需要检查自己的属性和实际对象,以防止分配不自己的属性。


0
投票

您可以使用function restructure(obj) { let newObj = {}; const newKeys = { fed_tax_id: 'federalTaxId', company_structure: 'companyStructure', home_number: 'homeNumber', customer: 'individual', first_name: 'firstName', last_name: 'lastName' }; for (let key in obj) { if (!obj.hasOwnProperty(key)) continue; newObj[newKeys[key] || key] = obj[key] && typeof obj[key] === 'object' ? restructure(obj[key]) : obj[key]; } return newObj; } console.log(restructure({ home_number: '1234', customer: { name: { last_name: 'Smith' } } }));Object.entries

© www.soinside.com 2019 - 2024. All rights reserved.