【问题标题】:Remove numbers from key of json in javascript从javascript中的json键中删除数字
【发布时间】:2013-10-13 23:08:21
【问题描述】:

我在 JSON 中发现以下输出为:

[{
    "ApplicationView": "",
    "Styling": "",
    "minwidth": "450px",
    "minheight": "350px",
    "kendoWindowWidth": "90%",
    "kendoWindowHeight": "90%",
    "iconSize": "20px",
    "viewerToolColor": "#8dcaf7",
    "DefaultView": "fit To Screen",
    "Email": "",
    "To": "ToPerson",
    "Subject": "This file is exported from actual program.",
    "From": "FromPerson",
    "Body": "This file is exported from actual program.",
    "Content": "",
    "zoomIn": "",
    "Icon16": "ZoomIn.png",
    "Label17": "Zoom In",
    "Visibility18": "true",
    "zoomOut": "",
    "Icon20": "ZoomOut.png",
    "Label21": "Zoom Out",
    "Visibility22": "true",
    "rotateLeft": null,
    "Icon24": "RotateLeft.png",
    "Label25": "Rotate Left",
    "Visibility26": "true",
    "rotateRight": "",
    "Icon28": "RotateRight.png",
    "Label29": "Rotate Right",
    "Visibility30": "true",
    "fitToScreen": "",
    "Icon32": "fittoscreen.png",
    "Label33": "Fit to Screen or Double Click on Image",
    "Visibility34": "true",
    "fullScreen": "",
    "Icon36": "fullscreen.png",
    "Label37": "Full Screen or 2 Times Double Click on Image",
    "Visibility38": "true",
    "saveAs": "",
    "Icon40": "download.png",
    "Label41": "Full Screen or 2 Times Double Click on Image",
    "Visibility42": "true",
    "print": "",
    "Icon44": "print.png",
    "Label45": "Print",
    "Visibility46": "true",
    "email": "Email",
    "Icon48": "email.png",
    "Label49": "Send Mail",
    "Visibility50": "true"
}]

我想从 JSON 的键中删除数字

示例:icon48 将是 icon

请指导我这样做。

我试图在foreach 循环中访问json 的键并使用正则表达式删除数字,但在执行此操作时没有成功。

我们将不胜感激。

【问题讨论】:

  • 首先,您有一个实际的 JSON 字符串,还是有一个 javascript 对象?其次,到目前为止,您尝试过什么? (给我们看一些代码)
  • 这个或类似的问题必须在 SO 上被回答至少 100 次。请搜索一下。
  • 我试过了,但没有一个成功。我从过去 5 小时开始一直在努力。
  • 所以你应该只使用“Icon”而不是“Icon16”?而不是“Icon20”,你也应该有“Icon”?他们不能有相同的钥匙?
  • 不,他们不能。当我使用时,钥匙被更换了。

标签: javascript regex json


【解决方案1】:

不要尝试直接处理 JSON 字符串:您真的应该在更改它之前对其进行解析。

var arr1 = JSON.parse(yourJSON);
var arr2 = arr1.map(function(o1){
    var o2 = {};
    for (var key in o1) {
        o2[key.replace(/\d+/g,'')] = o1[key];
    }
    return o2;
});
var finalJSON = JSON.stringify(arr2);

如果您实际上没有任何 JSON,而只是一个普通的 JavaScript 数组,请跳过第一步和最后一步。

Demonstration

【讨论】:

  • 不工作,先生。 myJsonString = JSON.stringify(yuiop); yuiop 是我推送所有值的数组的名称。
  • It works in my tests。你能检查一下你做的不同吗?
  • 尊敬的先生,检查您的演示。缩小后没有图标、标签和可见性显示。
猜你喜欢
  • 2016-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-24
  • 1970-01-01
  • 2021-05-29
  • 1970-01-01
相关资源
最近更新 更多