2017-02-10 48 views
1

我有一個任務,用字符串模式中的所有鍵替換它們的值。輸入是類似的東西:
用給定字符串模式中的值替換對象鍵

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

和輸出是這樣的:「我的名字是約翰和我13歲。」
於是我想出了這一點:

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); 
    } 
} 
} 

我有一個問題,當我CONSOLE.LOG(currentKey)我只拿到了零,但我的想法是走在輸入的第一個對象,然後json.parse它未來拿該對象中的所有鍵以及一個循環將分別取出每個單獨的鍵,並使用正則表達式將其替換爲模式字符串。但是這個Object.keys只返回零。哪裏有問題?

+1

你可以模擬它的jsfiddle? –

+0

我並沒有真正明白你打算做什麼。 – Connum

+0

對不起,輸出不是零。它是從'1'到'28'的數字。我的意圖是從一個對象中取出所有的鍵,並用它們的值替換它們的字符串模式。 – 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

嘗試其他方式,首先是解析模板字符串,然後遍歷,你需要這樣你就可以在對象直接引用它們的鑰匙。 另外,我不知道你想用參數對象做什麼。

// 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); 

只要你保持陣列從parseTemplate返回處於同一數量級,就可以重用任何參數多次在一個字符串,只要你想。數據中找不到的#{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

相關問題