简体   繁体   English

typescript:将字符串数组转换为自定义对象的逻辑

[英]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). 我能够在Java中达到一定水平,但我们需要将其移至打字稿(客户端)。

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. 技巧是递归地解析字符串并将中间结果存储在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)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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