我的字符串是:
var str = "hi {0} your contact is {1}";
{0},{1}表示我们可以替换为该字符串的动态数据。必须找到" {0}"并将其替换为数组中包含的对象:
var my_arr=[[{"data":"priya"},{"data":"reena"},{"data":"mathew"}],[{"data":"123456"},{"data":"745896"},{"data":"236521"}]]
我希望用my_arr [0]数据替换{0},用my_arr [1]数据替换{1}。最后我的输出将是这样的:
var result={"hi priya your contact is 123456","hi reena your contact is 745896","hi mathew your contact is 236521"}.
请帮我这样做,数组格式的任何更改都是可以接受的。提前谢谢。
答案 0 :(得分:0)
尝试以下代码。
var str = "hi {0} your contact is {1}";
var my_arr=[[{"data":"priya"},{"data":"reena"},{"data":"mathew"}],[{"data":"123456"},{"data":"745896"},{"data":"236521"}]]
var result = [];
$.each(my_arr[0],function(i) {
var str = "hi {0} your contact is {1}";
result.push(str.replace('{0}',my_arr[0][i].data).replace('{1}',my_arr[1][i].data));
});
console.log(result);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
答案 1 :(得分:0)
像这样使用nested loop
和string replace
var my_arr=[[{"data":"priya"},{"data":"reena"},{"data":"mathew"}],[{"data":"123456"},{"data":"745896"},{"data":"236521"}],[{"data":"address1"},{"data":"address2"},{"data":"address3"}]]
var str = "hi {0} your contact is {1} and address is {2}";
var new_arr =[];
for(i=0;i<my_arr.length;i++)
{
for(j=0;j<my_arr[i].length;j++)
{
if(i==0)
{
str_1 = str.replace("{"+i+"}",my_arr[i][j]['data']);
new_arr.push(str_1);
}
else
{
new_arr[j]=new_arr[j].replace("{"+i+"}",my_arr[i][j]['data']);
}
}
}
console.log(new_arr);
&#13;