简体   繁体   中英

typescript : logic to covert string array into custom object

Here is my requirement. I was able to achieve to some level in java but we need to move it to typescript (client side).

Note: The below input is for example purpose and may vary dynamically.

Input

var input = ["a.name", "a.type", "b.city.name" , "b.city.zip", "b.desc","c"];

We need to create an utility function that takes above input and returns output as below.

Output :

Should be string not an object or anything else.

"{ a { name, type }, b { city  {name, zip } , desc },  c }"

any help is much appreciated.

I don't see that typescript plays any role in your question, but here's a solution for constructing the string you requested. I first turn the array into an object with those properties, then have a function which can turn an object into a string formatted like you have

 const input = ["a.name", "a.type", "b.city.name" , "b.city.zip", "b.desc","c"]; const arrayToObject = (arr) => { return arr.reduce((result, val) => { const path = val.split('.'); let obj = result; path.forEach(key => { obj[key] = obj[key] || {}; obj = obj[key]; }); return result; }, {}); } const objectToString = (obj, name = '') => { const keys = Object.keys(obj); if (keys.length === 0) { return name; } return `${name} { ${keys.map(k => objectToString(obj[k], k)).join(', ')} }`; } const arrayToString = arr => objectToString(arrayToObject(arr)); console.log(arrayToString(input)); 

Here's another variation. Trick is to parse the strings recursively and store the intermediate results in an Object.

  function dotStringToObject(remainder, parent) { if (remainder.indexOf('.') === -1) { return parent[remainder] = true } else { var subs = remainder.split('.'); dotStringToObject(subs.slice(1).join('.'), (parent[subs[0]] || (parent[subs[0]] = {}))) } } var output = {}; ["a.name", "a.type", "b.city.name" , "b.city.zip", "b.desc","c"].forEach(function(entry) { dotStringToObject(entry, output) }); var res = JSON.stringify(output).replace(/\\"/gi, ' ').replace(/\\:|true/gi, '').replace(/\\s,\\s/gi, ', '); console.log(res) // Prints: { a { name, type }, b { city { name, zip }, desc }, c } 

You could do something like this:

 var input = ["a.name", "a.type", "b.city.name" , "b.city.zip", "b.desc","c"]; var output = {}; for(var i =0; i < input.length; i+=2){ output[String.fromCharCode(i+97)] = {}; output[String.fromCharCode(i+97)].name = input[i]; output[String.fromCharCode(i+97)].type = input[i+1]; } console.log(JSON.stringify(output)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM