Entonces, tengo esto:
const someFunction = () => { const facets = { names: { John: true, Mary: true }, nationalities: { US: true, CA: true } }; let final = { names: Object.keys(facets.names).join(" | "), nat: Object.keys(facets.nationalities).join(" | ") }; return final; }; let whatever = someFunction(); console.log(whatever);¿Cómo puedo crear otra función para devolver esta ruta y mostrar el valor original?
La pregunta de novato, lo sé.
Gracias
Sugeriría pasar el objeto de facets a la función como un parámetro, luego puede escribir fácilmente la entrada y la salida de la función:
const someFunction = (input) => { let final = { names: Object.keys(input.names).join(' | '), nat: Object.keys(input.nationalities).join(' | '), } return final; } const facets = { names: { John: true, Mary: true, }, nationalities: { US: true, CA: true, }, } const output = someFunction(facets) console.log('Input:', facets); console.log('Output:', output); .as-console-wrapper { max-height: 100% !important; top: 0; }Solución n. ° 1 : declarar facets en el nivel del módulo, para acceder a él fuera de someFunction :
const facets = { names: { John: true, Mary: true }, nationalities: { US: true, CA: true } }; // Your method: do the same, but simplified const someFunction = () => ({ names: Object.keys(facets.names).join(" | "), nat: Object.keys(facets.nationalities).join(" | ") }); // Reverted method: just return initial value const revertFuntion = () => facets Solución #2 : si necesita revertir cualquier valor devuelto por someFunction a su estado inicial, puede hacer algo como esto:
const revertChanges = obj => { for (const key in obj) { const res = {} obj[key].split(' | ').forEach(value => { res[value] = true; }) obj[key] = res; } return obj; } let whatever = someFunction(); console.log(whatever); // { // "names": "John | Mary", // "nat": "US | CA" // } let reverted = revertChanges(whatever); console.log(reverted); // Initial facetsNo estoy seguro de lo que quiere decir, pero si necesita tanto las facets como final , puede devolver un Object .
const someFunction = (facets, unify) => { const result = { names: Object.keys(facets.names).join(" | "), nat: Object.keys(facets.nationalities).join(" | ") }; return unify ? {...result, original: facets } : {original: facets, result}; }; const facets = { names: { John: true, Mary: true }, nationalities: { US: true, CA: true } }; const whatever = someFunction(facets); const pre = document.querySelector(`pre`); pre.textContent = `Object with original/result properties: ${ JSON.stringify(whatever, null, 2)}`; // or include facets as 'original' within the return value pre.textContent += `\n\nSingle object: ${JSON.stringify(someFunction(facets, true), null, 2)}`; <pre></pre>