将一个对象转换为对象数组,基于键中的子字符串分类。

4

我有一个对象长得像这样:

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" 
                        }
                       ]; 

我需要一个帮助函数来完成这个任务,这样我就可以将其存储在React状态中(函数组件)。

3个回答

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))


谢谢。我该如何将这个包装在一个返回数组“results”的函数中?我可能匆忙提问了,但我正在使用React,所以我需要将数组存储在状态中。我已经尝试自己将其包装在一个函数中,但它没有起作用。 - Kris
不客气。我已经将其封装在一个函数中,您可以在React组件外部使用它来转换源数据。 - ksav
谢谢。您的函数中有一个小错误,如果答案对其他人有帮助,可能值得进行编辑:results[+index][newKey] = srcObject[key] 应该改为 results[+index][newKey] = src[key]。 - Kris
谢谢你指出了这个问题。我已经采纳了你的建议并更新了答案。 - ksav

0

方法

  1. 通过拆分对象键来组织对象结构(因为顺序可能不同)
  2. 按公共键部分对它们进行分组
  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)


0

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);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接