我被卡住了。我想使用我的json中的数据,并使用相同的数据来编辑此json :(图像最好是说明性的) 我的JSON文件如下所示:
[{
"method": "GET",
"path": "/",
"aliases": "",
"name": "rootPath",
"handler": "generatedApps/avion01/actions.HomeHandler"
},
{
"method": "GET",
"path": "/avions/",
"aliases": "",
"name": "avionsPath",
"handler": "generatedApps/avion01/actions.AvionsResource.List"
},
{
"method": "GET",
"path": "/notifications/",
"aliases": "",
"name": "notificationsPath",
"handler": "generatedApps/avion01/actions.NotificationsResource.List"
},
{
"method": "POST",
"path": "/notifications/",
"aliases": "",
"name": "notificationsPath",
"handler":
"generatedApps/avion01/actions.NotificationsResource.Create"
}]
我想获取位于“路径”(avions或通知)中的参数,并创建一个名为“ ressourceName”的数据:“(如果path == avions或path ==通知)”
应该看起来像这样:
[{
"method": "GET",
"path": "/",
"aliases": "",
"name": "rootPath",
"handler": "generatedApps/avion01/actions.HomeHandler"
},
{
"ressourceName": "avions",
"method": "GET",
"path": "/avions/",
"aliases": "",
"name": "avionsPath",
"handler": "generatedApps/avion01/actions.AvionsResource.List"
},
{
"ressourceName": "notifications",
"method": "GET",
"path": "/notifications/",
"aliases": "",
"name": "notificationsPath",
"handler": "generatedApps/avion01/actions.NotificationsResource.List"
},
{
"ressourceName": "notifications",
"method": "POST",
"path": "/notifications/",
"aliases": "",
"name": "notificationsPath",
"handler":
"generatedApps/avion01/actions.NotificationsResource.Create"
}]
答案 0 :(得分:2)
您必须遍历项目并通过比较路径来更新项目:
items.forEach(item => {
if(item.path === '/avions/') {
item.ressourceName = 'avions':
} else if(item.path === '/notifications/') {
item.ressourceName = 'notifications':
}
})
答案 1 :(得分:0)
欢迎您!
对于这种情况,我假设您将其作为对象数组保存在节点代码中:var resources = JSON.parse('your incoming array')
如果是这样,则是遍历数组并将字段添加到每个对象的情况。广告名称与路径内容相同,您可以将斜杠去掉,并在出现其他路径时将其覆盖住
for(var i = 0 ; i < resources.length; i++){
var name = resources[i].path.replace(/\//g, '');
if(name !== ''){
resources[i].ressourceName = name;
}
}
console.log('resources',resources)
resources[i].path
是字符串格式的路径.replace()
将路径字符串中的出现替换为另一个字符串/\//g
是用于查找所有正斜杠/
''
是空字符串,将这些找到的斜杠替换为name !== ''
如果新名称只是一个空字符串(即路径为"/"
),则不要分配名称这会通过添加resourceName
属性来修改您的初始资源数组对象,但不会更改.path
属性。