4

I have an object that looks like this:

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",
}

I would like to manipulate this object so it gets transform in an array that looks like this base on the information for each user (ie, 1 or 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" 
                        }
                       ]; 

I will need to have a helper funcion to do it, so I can then store it in a react state (funcional component)

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. How can I wrap this in a funcion that returns the array "results". I might have rushed the question, but I am using React, so I need to store the array in a state. I have tried to wrap it in a funcion myself but it is not working.
You're welcome. I have wrapped this in a function that you can use outside of your react component to transform the source data.
Thank you. There is a small error in your funcion that might be worth editting in case the answer help others: results[+index][newKey] = srcObject[key] must be results[+index][newKey] = src[key]
Thanks for catching that. I have updated the answer with your suggestion.
0

The Approach

  1. Organize the object structure by splitting the object keys ( because the order many differ
  2. Group them by Common Key part
  3. Now collect into an array

Implementation

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)

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.