So here's an example:
{
"part": "Intro",
"e": "------5/6------8\\6-|-------------------|-------------------",
"B": "-----------9-------|---------6p8---(6)-|-------------------",
"G": "--8----------------|---8h9-------------|--<8>--------------",
"D": "",
"A": "",
"E": "",
"endMsg": "Continue..."
}
Note: The double-slash will turn into one slash only upon render of text.
I want to get value from this object that is not empty. (So that could be from the e key or from the B key. 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.
{ "part": "Intro", "e": "------5/6------8\\6-|-------------------|-------------------", "B": "-----------9-------|---------6p8---(6)-|-------------------", "G": "--8----------------|---8h9-------------|--<8>--------------", "D": "-------------------|-------------------|-------------------", "A": "-------------------|-------------------|-------------------", "E": "-------------------|-------------------|-------------------", "endMsg": "Continue..." }
I have no idea how to achieve this in code. Please help.
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 = {
"part": "Intro",
"e": "------5/6-----8\\6-|-------------------|-------------------",
"B": "-----------9-------|---------6p8---(6)-|-------------------",
"G": "--8----------------|---8h9-------------|--<8>--------------",
"D": "",
"A": "",
"E": "",
"endMsg": "Continue..."
};
const createFullLines = (lines, blacklist = ['part', 'endMsg']) => {
// Find a line that is not empty
const line = Object.entries(lines).find(([key, line]) => {
return !blacklist.includes(key) && line.trim();
});
// Exit if all lines are empty
if(!line) return lines;
// Destructure to get only value
const [_, filledLine] = line;
// Create new line with only dashes
const newLine = filledLine.replace(/[^-|]/g, '-');
// Update lines
for(const key in lines) {
lines[key] ||= newLine;
}
return lines;
}
const result = createFullLines(lines);
console.log(result);
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, '-');