So here's an example:
{
"e": "------5/6-----8\\6-|-------------------|-------------------",
"B": "-----------9-------|---------6p8---(6)-|-------------------",
"G": "--8----------------|---8h9-------------|--<8>--------------",
"D": "",
"A": "",
"E": ""
}
I want to get value from this object that is not empty. (So that could be from the
ekey or from theBkey. As long it's not empty.)Then I'm replacing that value using this expression here:
str.replace(/[0-9-. a-zA-Z // \ ~ ( ) < >]/g, '-');
It's for replacing the numbers, letters, and other characters into dashes.
- I want to use that value with the dashes and pipe chars only to fill up the other keys inside the same object that are empty.
- In the end, I want it to look something like this:
{ "e": "------5/6-----8\\6-|-------------------|-------------------", "B": "-----------9-------|---------6p8---(6)-|-------------------", "G": "--8----------------|---8h9-------------|--<8>--------------", "D": "-------------------|-------------------|-------------------", "A": "-------------------|-------------------|-------------------", "E": "-------------------|-------------------|-------------------" }
I have no idea how to achieve this in code. Please help.
CodePudding user response:
You should just iterate between your object's keys like this:
// find first non-empty field, !! - conversion to boolean
let nonEmptyKey = Object.keys(obj).find(key => !!obj[key]);
for(let key of Object.keys(obj)) {
// check if value is empty
if(!obj[key]) {
obj[key] = obj[nonEmptyKey].replace(/[0-9-. a-zA-Z // \ ~ ( ) < >]/g, '-');
}
}
Also, you can simplify your regex to this:
// replace all symbols except - and |
str.replace(/[^-|]/g, '-');
CodePudding user response:
You can loop over each key value pair and replace the value if its empty. Be aware that a backslash is used for escaping a character. To fix this we first replace the backslashes with dashes and then replace the rest.
The regex could also be simplified to /[^-|]/g which means replace all symbols except - and |
const lines = {
"e": "------5/6-----8\\6-|-------------------|-------------------",
"B": "-----------9-------|---------6p8---(6)-|-------------------",
"G": "--8----------------|---8h9-------------|--<8>--------------",
"D": "",
"A": "",
"E": ""
};
const createFullLines = (lines) => {
// Find a line that is not empty
const filledLine = Object.values(lines).find((line) => line.trim());
// Exit if all lines are empty
if(!filledLine) return lines;
// Create new line with only dashes
const newLine = filledLine.replace('\\', '--').replace(/[^-|]/g, '-');
// Update lines
for(const key in lines) {
lines[key] ||= newLine;
}
return lines;
}
const result = createFullLines(lines);
console.log(result);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
