Javascript - 重新映射 JSON,其中所有前缀属性都嵌套在前缀下



我从内部API获得的JSON数据完全平坦地返回给我,但每个类别都有一个属性的前缀,它应该嵌套在其中。在提供的示例中,前缀为 address_

示例 A - 当前格式:

{
  name: '',
  address_line1: '',
  address_city: '',
  address_state: '',
  address_country: '',
  phone: ''
}

示例 B - 所需格式:

{
  name: '',
  address: {
    line1: '',
    city: '',
    state: '',
    country: ''
  },
  phone: ''
}

实际数据非常广泛,但确实遵循相同的格式,因此我希望完成的是重新映射Example A以适应Example B格式,而无需手动写出 JSON 的每一行。

感谢您的时间和建议。

你可以做这样的事情:

const input = {
  name: '',
  address_line1: '',
  address_city: '',
  address_state: '',
  address_country: '',
  phone: ''
};
const output = Object.keys(input).reduce((a, key) => {
  if (key.includes('_')) {
    const [pKey, cKey] = key.split('_');
    if (a[pKey]) {
      a[pKey][cKey] = input[key];
    } else {
      a[pKey] = { [cKey]: input[key] };
    }
  } else {
    a[key] = input[key];
  }
  return a;
}, {});
console.log(output);

这仅适用于input对象的第一级,并且假定键将仅包含一个_字符,该字符将主键名称与嵌套对象的键名称分开。

受 Titus 的启发,这是我的版本,可以迭代一系列对象。

(工作代码笔示例(

const newJSON = users.map((data, index) => {
  return Object.keys(data).reduce((newObject, key) => {
    if (key.includes('_')) {
      const [header, nestedKey] = key.split('_')
      newObject[header] = {
        ...newObject[header],
        [nestedKey]: users[index][key]
      }
    } else {
      newObject[key] = users[index][key]
    }
    return newObject
  }, {})
})

最新更新