首页 > 解决方案 > 循环遍历 json 对象嵌套属性并在不为空时显示它们 - vue

问题描述

需要通过一个 JSON 对象,该对象可能有也可能没有“属性”字段,它可以为空,也可以有 10 个不同的,你不知道它们实际上叫什么,然后我需要在代码块中打印它, JSON数据在这里:

{
  "alias": "AS",
  "id": "4a4e1584-b0a7-4069-8851-0ee7f9e18267",
  "name": "asdfadf",
  "properties": {
    "shape": null,
    "units": "gms",
    "dimension": null,
    "maxWeight": "sdf",
    "minWeight": "asfd"
  },
}

输出需要是一个字符串,例如 Units: gms, MaxWeight: sdf... 或者这些可以是“大小”或其他人在额外属性中指定的任何内容,但它们将在属性下。

标签: javascriptjsonobject

解决方案


如果我正确理解您的问题,您需要查看properties对象内部(如果properties不为空)。

您只需要检查它是否不为空并循环遍历它。

let j = {
            "alias": "AS",
            "id": "4a4e1584-b0a7-4069-8851-0ee7f9e18267",
            "name": "asdfadf",
            "properties": {
                "shape": null,
                "units": "gms",
                "dimension": null,
                "maxWeight": "sdf",
                "minWeight": "asfd"
            },
}

if(j.properties !== null){
    for(let key in j.properties){
        console.log(` ${key} : ${j.properties[key]}`)
    }
}

如果您在 Vue 中需要帮助,您也可以将其包含在您的问题中,这样我们就可以准确地看到您正在尝试做什么。


推荐阅读