Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

194
Vistas
modify object property and add it to object as nested properties

I'm creating and populating an object with user input from x <input> fields. So far I've managed to create the object and populate it with the user input. However I'm stuck on my next step.

I want to grab and modify the user input and separate it into nested properties using comma to split.

This might be an easy task, but I can't come up with a working solution. How can I achieve this? (not sure how well I explained myself, so I posted an example for the desired output)

The html: (potentially more input fields than those 2x2)

<input type="text" name="test_1.Title" class="tests">
<input type="text" name="test_1.String" class="tests">
<input type="text" name="test_2.Title" class="tests">
<input type="text" name="test_2.String" class="tests">
function objectMaker() {

  function objectSubs(obj, keys, value) {
    let key = keys.shift()
    if (keys.length) {
      obj[key] = obj[key] || {}
      objectSubs(obj[key], keys,  value)
      return
    }
    obj[key] = value
  }

  function grabTestData(){
    var inputs = document.getElementsByClassName('tests');
    var testObject = {}
    Object.keys(inputs).forEach(i => {
      let inputName = inputs[i].getAttribute('name');
      objectSubs(testObject, inputName.split('.'), inputs[i].value)
    })
  }
  grabTestData()

}

current object:

var testObject = {
  tests1: {
    title: "random title",
    string: "somestring, other string, and anotherString",
  },
  tests2: {
    title: "other random title",
    string: "thisString, thatString, a String there",
  },
}

desired object:

var testObject = {
  tests1: {
    title: "random title",
    string: {
      substring1: "somestring",
      substring2: "other string",
      substring3: "and anotherString",
    },
  },
  tests2: {
    title: "other random title",
    string: {
      substring1: "thisString",
      substring2: "thatString",
    },
  },
}

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

If you want to make a function to convert the object over to your desired format:

function splitStrings(obj) {
  Object.values(obj).forEach(val => val.string = Object.fromEntries(val.string.split(',').map((e, i) => ["substring"+(i+1), e.trim()])));
  return obj;
}
  • takes the values of the object with Object.values to get an array of your { title, string } objects
  • forEach object, sets .string to an object created from converting each comma separated value in the string to an entry of format [substringN, value]

Demo:

var testObject = {
  tests1: {
    title: "random title",
    string: "somestring, other string, and anotherString",
  },
  tests2: {
    title: "other random title",
    string: "thisString, thatString, a String there",
  },
}

function splitStrings(obj) {
  Object.values(obj).forEach(val => val.string = Object.fromEntries(val.string.split(',').map((e, i) => ["substring"+(i+1), e.trim()])));
  return obj;
}

splitStrings(testObject);
console.log(testObject);


If you want an array of substrings instead, you can do:

function splitStrings(obj) {
  Object.values(obj).forEach(val => val.string = val.string.split(',').map(e=>e.trim());
  return obj;
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

var testObject = {
  tests1: {
    title: "random title",
    string: "somestring, other string, and anotherString"
  },
  tests2: {
    title: "other random title",
    string: "thisString, thatString, a String there"
  }
};
testObject.tests1.string = testObject.tests1.string.split(",");
testObject.tests2.string = testObject.tests2.string.split(",");
console.log(testObject);

The output for this code is:

{
  tests1: {
    title: 'random title',
    string: [ 'somestring', ' other string', ' and anotherString' ]
  },
  tests2: {
    title: 'other random title',
    string: [ 'thisString', ' thatString', ' a String there' ]     
  }
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda