2017-02-10 6 views
1

文字列パターンのすべてのキーをその値に置き換えるタスクがあります。入力は、そのようなものです:
オブジェクトキーを指定した文字列パターンの値に置き換えます。

[ 
    '{ "name": "John", "age": 13 }', 
    "My name is #{name} and I am #{age}-years-old" 
] 

、出力はこれです:「私の名前はジョンと私は13歳です」。
だから私はこの思い付く:私は(currentKey)をCONSOLE.LOGとき、私は問題がある

function FillTemplate() { 
if (arguments.length < 2 || arguments.length > 7) { 
    console.log('The input objects should be at least 1 and lesser than 7!'); 
} 

for (let i = 0; i <= arguments.length - 2; i += 1) { 
    JSON.parse(arguments[i]); 

    for (let j = 0; j < Object.keys(arguments[i]).length; i += 1) { 
     let currentKey = Object.keys(arguments[i])[j]; 
     console.log(currentKey); 
    } 
} 
} 

私はゼロのみを得たが、私の考えは、それが次の取るjson.parse、入力内の最初のオブジェクトを取るですそのオブジェクト内のすべてのキーと1つのループを持つすべてのキーを1つのキーごとに別々に取り出し、それを正規表現パターンでパターン文字列に置き換えます。しかし、このObject.keysはゼロだけを返します。問題はどこだ?ここで

+1

あなたはjsfiddleでそれをシミュレートすることができますか? –

+0

あなたがやろうとしていることは本当に得意ではありません。 – Connum

+0

出力がゼロでないことをよろしくお願いします。 '1'から '28'までの数字です。私の意図は、オブジェクトからすべてのキーを取得し、文字列パターンでtrynaをそれらの値に置き換えることです。 – user7460099

答えて

1

あなたが行く:

<script> 
var foo = { 
    "name" : "John", 
    "age" : 13 
} 
var string = "My name is #{name} and I am #{age}-years-old"; 

// Extract all templates (#{name}, #{age}, ...) 
var matches = string.match(/#{[a-zA-Z]+?}/g); 
if (matches) { 
    matches.forEach(function(templateStringToReplace) { 
     // Strip the special characters to dynamically get the indices of the object 
     templateString = templateStringToReplace.replace(/#|{|}/g, ""); 
     string = string.replace(templateStringToReplace, foo[templateString]) 
    }); 
} 

alert(string); 

0

をあなたがそうあなたがオブジェクトにそれらを直接参照することができる必要がキーの上に、ループ、最初のテンプレート文字列を解析し、周りに他の方法を試してみてください。 また、引数オブジェクトで何をしようとしているのか分かりません。

限り、あなたは配列がparseTemplateから返さ保つよう
// Our source array containing a data string and a template string 
var source = [ 
     '{"name": "John", "age": 13 }', 
     'My name is #{name} and I am #{age}-years-old' 
    ], 
    // helper function to grab all the parameters from a template string 
    parseTemplate = function parseTemplate(template) { 
     var regex = /#\{(.+?)\}/g, 
      parameters = [], 
      nextParameter; 
     do { 
      // this regexp will grab the next series of characters surrounded by #{} 
      nextParameter = regex.exec(template); 
      if (nextParameter) parameters.push(nextParameter[1]); 
     } 
     // as long as there are parameters left, keep searching 
     while (nextParameter); 
     return parameters; 
    }, 
    // population function, uses parseTemplate to get the parameters and then adds them to the template 
    populateTemplate = function populate(template, data) { 
     var parametersToSaturate = parseTemplate(template); 
     // for each parameter found, repalce that parameter in the string with the value from the data 
     return parametersToSaturate.reduce(function(saturatedTemplate, parameter) { 
      return saturatedTemplate.replace('#{' + parameter + '}', data[parameter] || ('#{' + parameter + '}')); 
     }, template); 
    }, 
    result = populateTemplate(source[1], JSON.parse(source[0])); 
console.log(result); 

が同じ順序で、あなたが好きな文字列に何回も任意のパラメータを再利用することができます。データに見つからない#{val}パラメータはそのまま残ります。

複数のオブジェクトがある場合は、それらをループすることができます。

sources.forEach(function(source) { 
    console.log(populateTemplate(source[1], JSON.parse(source[0]))); 
}); 

お使いのブラウザがそれをサポートしている場合は、実際のJSテンプレート文字列を使用することができます。 https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Template_literals

関連する問題