Javascript 如何通过给定的字符串名称动态创建对象?

Javascript 如何通过给定的字符串名称动态创建对象?,javascript,jointjs,Javascript,Jointjs,我正在尝试从给定的字符串创建对象。字符串值应该是新对象的名称。我创建了一个根对象,然后通过输入一个字符串名并从根对象克隆来创建后续对象 我正在使用jointJs 这是根对象 var lvl0 = new joint.shapes.basic.Rect({ position: { x: 100, y: 30 }, size: { width: 100, height: 30 }, attrs: { rect: { fill: '#31d0c6', stroke: 'none

我正在尝试从给定的字符串创建对象。字符串值应该是新对象的名称。我创建了一个根对象,然后通过输入一个字符串名并从根对象克隆来创建后续对象

我正在使用jointJs

这是根对象

var lvl0 = new joint.shapes.basic.Rect({
    position: { x: 100, y: 30 },
    size: { width: 100, height: 30 },
    attrs: { rect: { fill: '#31d0c6', stroke: 'none',  filter: { name: 'dropShadow',  args: { dx: 3, dy: 6, blur: 3, color: '#333333' }} }, 
             text: { text: 'lvl0', fill: '#ffffff' }, 
             style: { 'text-shadow': '1px 0 1px #333333' }  }

});
然后是克隆根对象并为新对象指定给定名称的函数

function add_cell(parent, child, lvl, color) {
  if (lvl === 0)
  { var child = parent.clone().translate(0, 0).attr('text/text', child);  }
  else { var child = parent.clone().translate(200, 0).attr('text/text', child).attr('rect/fill', color); }
  graph.addCell(child);
  if (lvl != 0) {  createLink(parent, child).set(createLabel('0,N     1,1')); }
}
这是呼叫代码

var lst = [ { "parent": "lvl0", "child": "dept", "lvl": 0, "color": "green" }, { "parent": "dept", "child": "empl", "lvl": 1, "color": "yellow" } ];
for (var i = 0; i < lst.length; i++) {
  add_cell (window[lst[i].parent], lst[i].child, lst[i].lvl, lst[i].color);
}
var lst=[{parent:“lvl0”,“child:“dept”,“lvl”:0,“color:“green”},{parent:“dept”,“child:“empl”,“lvl”:1,“color:“yellow”}];
对于(变量i=0;i
第一次克隆成功,因为要克隆的对象lvl0是现有对象。但是第二个克隆将失败,因为对象dept不存在。相反,子变量将覆盖到克隆对象。我基本上需要将克隆对象从child重命名为dept。我该怎么做


谢谢,

问题不清楚