从字符串变量解析数据

时间:2018-06-09 17:57:28

标签: javascript jquery string variables

我想解析字符串变量中的数据,例如我有一个数据:

resData = [
            {
             id: 1,
             name: 'Jack',
             full_name: 'Jack Sparrow',
             avatar_url: 'http://example/img.jpg',
             ....
            },
            {
             id: 2,
             name: 'Elly',
             full_name: 'Elly Tran',
             avatar_url: 'http://example/elly.jpg',
             ....
            }
          ]

let dataStr = {
             id: 'data.id',
             html: '<strong>{{data.name}}</strong>',
             title: '<h3>{{data.full_name}}</h3>',
             icon: '{{data.avatar_url}}'
           }

现在我如何将resData与dataStr之类的格式转换为:

dataFormated = [
            {
             id: 1,
             name: '<strong>Jack</strong>',
             full_name: '<h3>Jack Sparrow</h3>',
             avatar_url: 'http://example/img.jpg'
            },
            {
             id: 2,
             name: '<strong>Elly</strong>',
             full_name: '<h3>Elly Tran</h3>',
             avatar_url: 'http://example/elly.jpg'
            }
          ]

我使用了eval(),但没有解析字符串包含HTML,例如&#34; name&#34;,&#34; full_name&#34;,...

编辑!

2 个答案:

答案 0 :(得分:0)

我已经更新了我的答案。请再次检查

var dataFormated = [];
var index = 0;
for (var i in resData) {
    dataFormated[index] = {
        id: resData[i].id,
        html: '<strong>' + resData[i].name + '</strong>',
        title: '<h3>' + resData[i].full_name + '</h3>',
        icon: resData[i].avatar_url
    };
    index += 1;
}

答案 1 :(得分:0)

您可以使用以下任一项:

let dataFormated = resData.map(obj => (
    {
        id: obj.id,
        html: `<strong>${obj.name}</strong>`,
        title: `<h3>${obj.full_name}</h3>`,
        icon: obj.avatar_url
    }
))

let dataFormated = resData.map(obj => (
    {
        id: obj.id,
        html: '<strong>' + obj.name + '</strong>',
        title: '<h3>' + obj.full_name + '</h3>',
        icon: obj.avatar_url
    }
))

或 使用正常功能如下:

let dataFormated = resData.map(function(obj){
    return {
            id: obj.id,
            html: '<strong>' + obj.name + '</strong>',
            title: '<h3>' + obj.full_name + '</h3>',
            icon: obj.avatar_url
        };
})