Estoy creando y completando un objeto con la entrada del usuario de x campos <input> . Hasta ahora he logrado crear el objeto y completarlo con la entrada del usuario. Sin embargo, estoy atascado en mi siguiente paso.
Quiero capturar y modificar la entrada del usuario y separarla en propiedades anidadas usando una coma para dividir.
Esta podría ser una tarea fácil, pero no puedo encontrar una solución que funcione. ¿Cómo puedo conseguir esto? (No estoy seguro de qué tan bien me expliqué, así que publiqué un ejemplo para el resultado deseado)
El html: (potencialmente más campos de entrada que esos 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() }objeto actual:
var testObject = { tests1: { title: "random title", string: "somestring, other string, and anotherString", }, tests2: { title: "other random title", string: "thisString, thatString, a String there", }, }objeto deseado:
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", }, }, }Si desea crear una función para convertir el objeto a su formato deseado:
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; }Object.values para obtener una matriz de sus { title, string } objetosforEach object, establece .string en un objeto creado a partir de la conversión de cada valor separado por comas en la cadena a una entrada de formato [substringN, value]Manifestación:
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);Si desea una matriz de subcadenas en su lugar, puede hacer:
function splitStrings(obj) { Object.values(obj).forEach(val => val.string = val.string.split(',').map(e=>e.trim()); return obj; }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);La salida para este código es:
{ tests1: { title: 'random title', string: [ 'somestring', ' other string', ' and anotherString' ] }, tests2: { title: 'other random title', string: [ 'thisString', ' thatString', ' a String there' ] } }