I have a string with comma separated values in json file and want to convert it to a list to iterate through for loop and click on each element.Please help me on this !
testdata.json :
{"optionsList":"China - English,France - English,South Korea - English,Japan - English,Brazil - English"}
code:
var optionsLocator="//a[normalize-space()='%d']"; this.verifyOptionsList=async function(){ let options = await getTestData(testData, "optionsList"); var listOfOptions=JSON.parse(JSON.stringify(options)); logger.info("options list : ", listOfOptions); for (let i = 0; i < listOfOptions.length; i++) { var replaceOption = optionsLocator.replace("%d", listOfOptions[i]); logger.info("Search Option :",replaceOption); var optionLoc = element(by.xpath(replaceOption)); await clickElement(optionLoc); } }
output :
options list : China - English,France - English,South Korea - English,Japan - English,Brazil - English Search Option : '//a[normalize-space()='C']'
Advertisement
Answer
I think the easiest way is to do it by parts, you can first remove the -
using the split
function, then it will result into an array like:
[ "China", "English,France", "English,South Korea", "English,Japan", "English,Brazil", "English" ]
then iterating over each one of the strings and using split
you will be able to separate the strings that has ,
. resulting in something like:
[ [ "China" ], [ "English", "France" ], [ "English", "South Korea" ], [ "English", "Japan" ], [ "English", "Brazil" ], [ "English" ] ]
then you can flat
this array using the function flat
of the arrays.
here you ahve a working sample:
const response = { "optionsList": "China - English,France - English,South Korea - English,Japan - English,Brazil - English" } const options = response.optionsList const splitByDash = options.split(' - '); const splitByComa = splitByDash.map(str => str.split(",")) const result = splitByComa.flat(); console.log(result)