javascript对象初始化{key:val,string}

时间:2016-02-24 07:47:17

标签: javascript object properties

我需要创建一个具有常量第一个键属性的对象。其余的都是动态的(来自db) 我的解决方案是...... 让我们这样说:

var bar="bar"; //comes from db;
var myProperties="trick":"treat","man":"woman"; // comes from db
var obj = {"foo":bar, myProperties}

但我有一个错误。我不知道如何处理这个要求。

人?替代解决方案?

2 个答案:

答案 0 :(得分:1)

您应合并属性:

 function merge_options(obj1,obj2){
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
 }

 var bar="bar"; //comes from db;
 var myProperties={trick:"treat",man:"woman"}; // comes from db
 var obj = merge_options({"foo":bar}, myProperties);

或者更简单地创建对象并设置foo属性:

var obj={trick:"treat",man:"woman"};
obj.foo=bar;

答案 1 :(得分:0)

var object = new Object();     var obj = {“foo”:bar}

var myProperties="trick":"treat","man":"woman"; // comes from db

var object = myProperties.slipt(",");

for(var i=0; i < object.length ; i++){
    var item = object[i];

    obj.push(item);
}

// obj = {"foo":bar, "trick": treat, "man": woman} 

return obj;