有一个棘手的问题,只能在 SO 上看到类似但也更简单的解决方案。
是否可以使用 JS/JSON 生成动态键和动态值?
例如,假设我有这样的 JSON:
{
"email": "user@someco.com",
"firstname": "Bob",
"lastname": "Smith",
"company": "ACME",
"custom": {
"services": [
{
"name": "svc1",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc2",
"desc": "abcdefg",
"selected": "true",
"status": "None"
},
{
"name": "svc3",
"desc": "abcdefg",
"selected": "false",
"status": "None"
},
{
"name": "svc4",
"desc": "abcdefg",
"selected": "false",
"status": "None"
}
],
"fields": [
{
"name": "Products",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Product1",
"desc": "abcdef"
},
{
"name": "Product2",
"desc": "abcdef"
}
],
"services": [
"svc1",
"svc2",
"svc3"
]
},
{
"name": "Wines",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Wine 1",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
},
{
"name": "Fruits",
"desc": "abcdef",
"type": "multi",
"values": [
{
"name": "Fruit 1",
"desc": "abcdef"
},
{
"name": "Fruit 2",
"desc": "abcdef"
}
],
"services": [
"svc4"
]
}
]
}
};
我需要进入各个领域并为每个领域(产品、葡萄酒、水果)查看是否包含给定的服务,以便我可以返回并为需要它的每项服务生成产品或葡萄酒或水果。但我不想多次重复服务名称。生成的 JSON 应如下所示:
{"svc1":["Products"], "svc2":["Products"], "svc3":["Products"], "svc4":["Fruits", "Wines"]}
希望在 Angular 中生成一个动态列表,我可以通过这个 JSON 循环返回,提取每个产品、水果、葡萄酒等的值。
我一直在尝试很多嵌套的 for 循环等,但是每当我向下一层以上时,动态似乎就会停止。我猜要让它工作,我需要在 JS 对象和 JSON 之间移动?
现在我正在尝试这样的事情,它不太工作,stringify or no。也许我在 JSON 和 JS 对象之间来回切换太多:
var outObj = [];
var fieldItems;
$.each(jsonObj.custom.fields, function(key, item) {
fieldItems = item;
fieldItems.name = item.name;
$.each(fieldItems.services, function(key, item) {
var serviceName = item;
//check to see if the serviceName already exists
if (outObj.indexOf(serviceName) > -1) {
outObj.serviceName.push(fieldItems.name);
} else {
outObj.push(serviceName);
}
});
});
JSON.stringify(outObj);
console.log("outObj " + outObj);
我收到“无法读取未定义的属性‘推送’”错误等。似乎这应该可以从一个嵌套循环中实现,但也许我只需要做两次传递?还有其他建议吗?