2017-02-10 49 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

相关问题