javascript - 循环遍历 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... 或者这些可以是“大小”或其他人在额外属性中指定的任何内容,但它们将在属性下。
解决方案
如果我正确理解您的问题,您需要查看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 中需要帮助,您也可以将其包含在您的问题中,这样我们就可以准确地看到您正在尝试做什么。
推荐阅读
- zero - 返回 tableau 中列/行中的第一个非零值
- java - 为什么这段 Java 代码会产生这个输出
? - sql-server - 在 SQL Server 中插入不使用空白作为默认值
- javascript - React 渲染 HTML 代码 (dangerouslySetInnerHTML?)
- java - 在不停止应用程序的情况下将 JAR 添加到类路径
- django - Django 序列化 KeyError (Django Rest 框架)
- python - 如何在 Python 的表达式中获取字母
- java - 骆驼失败的核心测试用例
- javascript - 通知点击事件服务工作者
- java - android studio 媒体播放器空对象引用