如何使用forEach循环添加Json项?

时间:2017-06-21 11:13:10

标签: javascript json

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

3 个答案:

答案 0 :(得分:1)

为什么在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);

答案 1 :(得分: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() 
    })
}

答案 2 :(得分:0)

如果您需要map

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