So, I have this:
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);
How can I create another function to return this path and show the original value?
The rookie question, I know.
Thank you
I'd suggest passing the facets object to the function as a parameter, you can then easily write the input and output of the function:
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; }
Solution #1:
Declare facets on module level, for accessing to it outside of 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
Solution #2:
if you need to revert any value returned by someFunction to it's inital state, you can do something like this:
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 facets
Not sure what you mean, but if you need both facets and final you can return an 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>