从json中删除特定元素

时间:2016-02-19 09:38:19

标签: javascript json

我有json喜欢

{
  "type": "textbox",
  "originX": "center",
  "originY": "top",
  "left": 1289.6,
  "top": 695.43,
  "width": 244.84,
  "height": 36.72,
  "fill": "rgb(0, 0, 0)",
  "stroke": null,
  "strokeWidth": 1,
  "strokeDashArray": null,
  "strokeLineCap": "butt",
  "strokeLineJoin": "miter",
  "strokeMiterLimit": 10,
  "scaleX": 1,
  "scaleY": 1,
  "angle": 0,
  "flipX": false,
  "flipY": false,
  "opacity": 1,
  "shadow": null,
  "visible": true,
  "clipTo": null,
  "backgroundColor": "",
  "fillRule": "nonzero",
  "globalCompositeOperation": "source-over",
  "transformMatrix": null,
  "lockMovementX": false,
  "lockMovementY": false,
  "evented": true,
  "text": "FROM ONLY £199",
  "fontSize": 25,
  "fontWeight": "",
  "fontFamily": "'trebuchet ms'",
  "fontStyle": "",
  "lineHeight": 1.3,
  "textDecoration": "",
  "textAlign": "left",
  "textBackgroundColor": "",
  "styles": {
     "0": {
       "1": {
        "fontFamily": "'trebuchet ms'",
        "fontSize": 25,
        "fontWeight": "",
        "fontStyle": ""
      },
      "2": {
        "fontFamily": "'trebuchet ms'",
        "fontSize": 25,
        "fontWeight": "",
        "fontStyle": ""
      }
    }
  },
  "minWidth": 20
}

你可以看到后面有styles属性,它有许多其他对象。当你打开一个时,你会看到fontFamilyfontSize fontWeight。我想从中删除fontWeight。为此,我尝试了这段代码

if (typeof indexs['styles'] != "undefined") {
    for (rowIndex in indexs['styles']) {
        for (letterIndex in indexs['styles'][rowIndex]) {
           if (indexs['styles'][rowIndex][letterIndex].fontWeight && indexs['styles'][rowIndex][letterIndex].fontWeight=='') {
               delete indexs['styles'][rowIndex][letterIndex]['fontWeight'];
            }
        }
    }   
}

但不删除该属性。我在那里做错了吗?

2 个答案:

答案 0 :(得分:1)

你必须更新这个:

if (indexs['styles'][rowIndex][letterIndex].fontWeight=='') {
    delete indexs['styles'][rowIndex][letterIndex]['fontWeight'];
}

因为空值""是假值而且

indexs['styles'][rowIndex][letterIndex].fontWeight

结果为false,而&&在两者都为true时应该有效。

答案 1 :(得分:1)

试试这个......检查键是否" fontWeight"在检查空值之前是否存在...

if (typeof indexs['styles'] != "undefined") {
    for (rowIndex in indexs['styles']) {
        for (letterIndex in indexs['styles'][rowIndex]) {
           if (indexs['styles'][rowIndex][letterIndex].hasOwnProperty("fontWeight") && indexs['styles'][rowIndex][letterIndex].fontWeight=='') {
               delete indexs['styles'][rowIndex][letterIndex]['fontWeight'];
            }
        }
    }   
}
});
相关问题