javascript - 使用 .map 将对象添加到数组时出现意外标记 {

标签 javascript arrays object dictionary

var $scope={};
var componentsDir="/root/";
var appPrefix="/app/";


var scriptRef=[];
function proDir(scriptName){
    return componentsDir+appPrefix+'-home-components/pro/js/'+scriptName+'.js';
};

var scriptList =[
            {s_name:'jquery',file:"jquery.js"},
            {s_name:'bootstrap',file:"bootstrap.min.js"},
            {s_name:'easing',file:"jquery.easing.min.js"},
            {s_name:'fittext',file:"jquery.fittext.js"},
            {s_name:'wow',file:"wow.min.js"},
            {s_name:'creative', file:"creative.js"},

            /*{bootstrap :"bootstrap.min.js"},
            {easing :"jquery.easing.min.js"},
            {fittext :"jquery.fittext.js"},
            {wow :"wow.min.js"},
            {creative :"creative.js"},*/
        ]



var newscript = scriptList.map(function(scriptItem){
    console.log(scriptItem)
    return {{scriptItem.s_name:'jquery'},{scriptItem.file:proDir(scriptItem.file)}},
});

console.log(newscript)

我尝试找到一种方法来循环遍历脚本列表,并使用 .map 向每个元素添加额外的目录信息。但我收到错误

Uncaught SyntaxError: Unexpected token {

我尝试将每个元素作为新 newscript 数组的对象返回

最佳答案

{ 不是 JSON 中 { 后面的有效字符。

替换这一行:

return {{scriptItem.s_name:'jquery'},{scriptItem.file:proDir(scriptItem.file)}}

用这一行:

return {"scriptItem.s_name": 'jquery', "scriptItem.file": proDir(scriptItem.file)}

或者另一个变体可能是:

return {
    scriptItem: {
        s_name: 'jquery',
        file: proDir(scriptItem.file)
    }
};

这是您在评论中要求的变体“我想像这样访问 newscript 的位置值:newscript.jquery:

var newscript = scriptList.map(function(scriptItem) {
    var returnval = {};
    returnval[ scriptItem.s_name ] = scriptItem.file;
    return returnval;
});

我认为您遇到了这个问题:

How can i name object "keys" programmatically in JavaScript?

如有疑问:

http://jsonlint.com/

关于javascript - 使用 .map 将对象添加到数组时出现意外标记 {,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31766895/

相关文章:

javascript - 如何在猴子修补过程中替换 eval() ?

javascript - 如何按数组字段值javascript对数组进行排序

java - 从数组设置类属性

java - 如何将类对象转换为通用对象类型?

javascript - 为什么不将类添加到已加载的导航元素中?

javascript - 如何附加可访问 html 属性的 jquery ui 元素?

javascript - 自动填充 0 值到未定义的 xAxes

java - 需要帮助创建数组

javascript - JS : strange result while accessing to arguments by key

python - 为什么 Python 中的整数需要三倍的内存?