2017-06-21 67 views
0

这是GoJS(图表化)项目的一部分,“属性”是itemArray,它是在图表中的一个节点内部定义的。如何使用forEach循环添加Json项目?

1)这工作(硬编码值):

properties: [ 
    { "property_name": "Prop1", "property_value": "100"}, 
    { "property_name": "Prop2", "property_value": "101" }, 
    { "property_name": "Prop3", "property_value": "102" } 
] 

2)该不工作(从数据源):

properties: [ 
    data.ObjectPropertiesList.forEach(function (item, i) { 
     properties.push({ "property_name": item.Item1.toString(), "property_value": item.Item2.toString() }); 
    }) 
] 

2.1)同周围的代码:

myPalette.model = new go.GraphLinksModel([ 
    { key: "B", text: "some block", color: "blue" }, 
    { key: "G", text: "Macro", isGroup: true }, 
    { category: "circle", key: "Gc", text: "A", color: "black", group: "G", loc: "0 0" }, 
    { 
     category: "table", key: "Ga", group: "G", loc: "60 0", 
     properties: [ 
      data.ObjectPropertiesList.forEach(function (item, i) { 
       properties.push({ "property_name": item.Item1.toString(), "property_value": item.Item2.toString() }); 
      }) 
     ] 
    } 
], [ 
    { from: "Gc", to: "Ga" } 
]); 
+0

可以请你也张贴你已经张贴在这里 –

回答

0

不要使用forEach当y ou want map

properties: data.ObjectPropertiesList.map(function (item) { 
    return { "property_name": item.Item1.toString(), "property_value": item.Item2.toString() }; 
}) 
+0

这个工程的第二个例子的sorrounding代码,但为什么不使用的forEach? – tesicg

+0

因为它是使用'map'的最好例子。你有一个你想修改每个元素并返回新数组的输入数组。这正是map所做的,它转换数组项并返回它们。 – str

0
var properties = []; 
for(var i=0; i < data.length; i++){ 
    var item = data[i]; 
    properties.push({ 
     "property_name": item.Item1.toString(), 
     "property_value": item.Item2.toString() 
    }) 
} 
0

为什么要在var声明中推送数据?刚刚宣布你的数组,然后将值,请参见下面的代码片段工作

var data= {}; 
 
    data.ObjectPropertiesList = [ 
 
    {Item1:"Prop1",Item2:"100"}, 
 
    {Item1:"Prop2",Item2:"101"}, 
 
    {Item1:"Prop3",Item2:"102"}, 
 
] 
 

 
properties = []; 
 

 
data.ObjectPropertiesList.forEach(function (item, i) { 
 
    properties.push({ "property_name": item.Item1.toString(), "property_value": item.Item2.toString() }); 
 
}) 
 

 
console.log(properties);

+0

很棒:) @tesicg –