[英]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.