2016-07-12 67 views
0

我有我需要的JSON对象。javasccript - 创建新对象

const tpl = require('../../../../assets/jsons/article-tpl.json');

然后,我通过遍历数组,我想使用这个对象在每个迭代上创建,因为它是在article-tpl.json定义一个新的模板。

angular.forEach(content.posts, (val, key) => { 
     let _tpl = new Object(tpl); 
     // do some things with _tpl 
     // push _tpl to array to hold all the different tplts 
    } 
}); 

此代码不起作用。 我得到一组相同的模板。你能帮我弄清楚是什么问题吗? 谢谢。

+4

请问您可以添加一些更多的代码或提供一个plunker? – varit05

+1

请尝试以下技巧:'let _tpl = JSON.parse(tpl);' –

+0

@AlexM那真的很好。我用'_tpl = JSON.parse(JSON.stringify(tpl));'因为它已经是一个对象而不是一个字符串。最终使用lodash'cloneDeep'。 –

回答

0

require语句仅适用于node.js,JavaScript/Angular中没有require

您可以使用$http请求(来自本地)而不是远程下载将Angular JSON加载到Angular中,并根据需要将其用于Angular。

例子:

var myObject = $http.get('myObject.json') 
       .then(
        function success(res) { 
        return res.data; 
        }, 
        function failed(err) { 
        console.log(err) 
        } 
       ); 

res.data是可以重复提取你所需要的,并作为模板使用数组。

我使用类似的东西将CSV转换为JSON in this gist

+0

你可以使用browserify(http://browserify.org/)在前端实际使用'require',问题不在 –

+0

是的,对。 “新对象”是最好的方法吗? –

+0

没有提到我使用的是webpack。这就是为什么要求 –

0

lodash救援。

let _tpl = _.cloneDeep(tpl);解决了它。

+1

最好向您发布的代码添加解释以作为答案,这样可以帮助访问者理解为什么这是一个很好的答案。 – abarisone