2017-06-21 71 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 –