簡體   English   中英

如何使用forEach循環添加Json項目?

[英]How to add Json items using forEach loop?

這是GoJS(圖表)項目的一部分,“屬性”是itemArray,它在圖中的一個節點內定義。

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" }
]);

為什么將數據放入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); 

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() 
    })
}

需要map時不要使用forEach

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM