【问题标题】:Convert an object into an array of objects base on a substring in the keys根据键中的子字符串将对象转换为对象数组
【发布时间】:2021-10-24 13:08:58
【问题描述】:

我有一个看起来像这样的对象:

const object = {
User 1 Fecha de Nacimiento: "02/05/2000",
User 1 Porcentage: 25,
User 1 Primer Apellido: "Gonzalez",
User 1 Segundo Apellido: "Perez",
User 1 Sexo: "H",
User 1 nombre: "Manuel",
User 2 Fecha de Nacimiento: "02/05/2000",
User 2 Porcentage: 25,
User 2 Primer Apellido: "Diaz",
User 2 Segundo Apellido: "Rodriguez",
User 2 Sexo: "M",
User 2 nombre: "Pepa",
}

我想操作这个对象,让它根据每个用户的信息(即 1 或 2)在一个看起来像这样的数组中进行转换:

const arrayOfObjects = [
                        {
                         Fecha de Nacimiento: "02/05/2000",
                         Porcentage: 25,
                         Primer Apellido: "Gonzalez",
                         Segundo Apellido: "Perez",
                         Sexo: "H",
                         Nombre: "Manuel"
                        }, 
                        {
                         Fecha de Nacimiento: "02/05/2000",
                         Porcentage: 25,
                         Primer Apellido: "Diaz",
                         Segundo Apellido: "Rodriguez",
                         Sexo: "M",
                         Nombre: "Pepa" 
                        }
                       ]; 

我需要一个辅助函数来执行此操作,因此我可以将其存储在反应状态(功能组件)中

【问题讨论】:

    标签: javascript arrays reactjs object


    【解决方案1】:

    const srcObject = {
      "User 1 Fecha de Nacimiento": "02/05/2000",
      "User 1 Porcentage": 25,
      "User 1 Primer Apellido": "Gonzalez",
      "User 1 Segundo Apellido": "Perez",
      "User 1 Sexo": "H",
      "User 1 nombre": "Manuel",
      "User 2 Fecha de Nacimiento": "02/05/2000",
      "User 2 Porcentage": 25,
      "User 2 Primer Apellido": "Diaz",
      "User 2 Segundo Apellido": "Rodriguez",
      "User 2 Sexo": "M",
      "User 2 nombre": "Pepa",
    }
    
    
    const transformData = (src) => {
      const results = [];
      Object.keys(src).forEach(key => {
        const split = key.split(/^User (\d+) /).filter(i => i !== '')
        const index = +split[0] - 1
        const newKey = split[1]
        if (!results[+index]) {
          results[+index] = {}
        }
        results[+index][newKey] = src[key]
      })
      return results
    }
    
    
    
    
    console.log(transformData(srcObject))

    【讨论】:

    • 谢谢。如何将其包装在返回数组“结果”的函数中。我可能已经匆忙提出这个问题,但我使用的是 React,所以我需要将数组存储在一个状态中。我自己尝试将它包装在一个函数中,但它不起作用。
    • 不客气。我已将其包装在一个函数中,您可以在反应组件之外使用该函数来转换源数据。
    • 谢谢。您的函数中有一个小错误可能值得编辑,以防答案对其他人有帮助:results[+index][newKey] = srcObject[key] must be results[+index][newKey] = src[key]跨度>
    • 感谢您的关注。我已根据您的建议更新了答案。
    【解决方案2】:

    const object = {
          "User 1 Fecha de Nacimiento": "02/05/2000",
          "User 1 Porcentage": 25,
          "User 1 Primer Apellido": "Gonzalez",
          "User 1 Segundo Apellido": "Perez",
          "User 1 Sexo": "H",
          "User 1 nombre": "Manuel",
          "User 2 Fecha de Nacimiento": "02/05/2000",
          "User 2 Porcentage": 25,
          "User 2 Primer Apellido": "Diaz",
          "User 2 Segundo Apellido": "Rodriguez",
          "User 2 Sexo": "M",
          "User 2 nombre": "Pepa",
          }
    
          var obj = {};
    
          for (const [key, value] of Object.entries(object)) {
            
            let splitedData = key.match(/User\s\d/);
            if (splitedData) {
              let user = splitedData[0];
              if (!obj[user])
                obj[user] = {};
    
              let prop = key.replace(/User\s\d/i, '').trim();
              obj[user][prop] = value;
            }
          }
    
          let outPut = Object.values(obj);
          console.log(outPut);

    【讨论】:

      【解决方案3】:

      方法

      1. 通过拆分对象键来组织对象结构(因为许多顺序不同
      2. 按 Common Key 部分对它们进行分组
      3. 现在收集到一个数组中

      实施

      var obj = {
        "User 1 Fecha de Nacimiento": "02/05/2000",
        "User 1 Porcentage": 25,
        "User 1 Primer Apellido": "Gonzalez",
        "User 1 Segundo Apellido": "Perez",
        "User 1 Sexo": "H",
        "User 1 nombre": "Manuel",
        "User 2 Fecha de Nacimiento": "02/05/2000",
        "User 2 Porcentage": 25,
        "User 2 Primer Apellido": "Diaz",
        "User 2 Segundo Apellido": "Rodriguez",
        "User 2 Sexo": "M",
        "User 2 nombre": "Pepa",
      }
      
      
      
      const getPrefixAndSuffix = (str = "", value) => {
      
        //console.log("::", str)
        var index = str.indexOf(' ', str.indexOf(' ') + 1);
      
        var firstChunk = str.substr(0, index);
        var secondChunk = str.substr(index + 1);
      
      
        return {
          prefix: firstChunk,
          suffix: secondChunk,
          value: value
        }
      
      }
      
      function groupBy(list, keyGetter) {
        const map = new Map()
        list.forEach(item => {
          const key = keyGetter(item)
          const collection = map.get(key)
          if (!collection) {
            map.set(key, [item])
          } else {
            collection.push(item)
          }
        })
        return map
      }
      
      const getAsList = (groups = {}) => {
      
        const valuesArr = []
        groups.forEach((value, key, map) => {
      
          var resultObj = {}
      
          value.forEach(value => {
            resultObj[value.suffix] = value.value
          })
      
          valuesArr.push(resultObj)
        });
      
        return valuesArr
      
      }
      
      const getFormatted = (obj) => {
      
        const asSplitList = Object.keys(obj).map((key) => {
      
          return getPrefixAndSuffix(key, obj[key])
      
        })
      
        const groupedItems = groupBy(asSplitList, (it) => it.prefix)
        return groupedItems
      
      }
      
      
      
      var format = getFormatted(obj)
      const finalList = getAsList(format)
      
      console.log(finalList)

      【讨论】:

        猜你喜欢
        • 2014-11-28
        • 2022-11-10
        • 2021-07-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-08
        • 1970-01-01
        相关资源
        最近更新 更多