javascript - 使用此示例 json 循环访问复杂和嵌套的 JSON
问题描述
我正在尝试循环一个复杂/嵌套的 JSON 对象。我正在尝试循环var_color.color.primary
。
问题:
是什么导致了这个错误?
无法读取未定义的属性“_id”
我怎样才能输出初级?
请仅使用 vanilla Javascript。
Example Data
products.json file
{
"products": [
{
"_id": "000",
"name": "Name 1",
"description": "Long description 1"
},
{
"_id": "001",
"name": "Name 2",
"description": "Long description 2",
"var_color": {
"_id": "12341",
"color": {
"primary": "pink",
"secondary": "penk"
}
}
},
{
"_id": "002",
"name": "Name 3",
"description": "Long description 3"
},
{
"_id": "003",
"name": "Name 4",
"description": "Long description 4",
"var_color": {
"_id": "12342",
"color": {
"primary": "red",
"secondary": "rid"
}
}
}
],
"categories": []
}
// main.js
async function getData(product) {
let response = await fetch(`./api/products/${product}`);
let data = await response.json();
return data;
}
getData('products.json').then(data => {
for (let i in data.products) {
let all = data.products[i];
let name = all.name;
let description = all.description;
console.log(name);
console.log(description);
for (let j in all) {
let variantColor = all.var_color[j].primary;
console.log(variantColor);
}
}
});
这是我目前的脚本。
解决方案
all.var_color
每个条目中都不存在,因此您需要检查它的存在。您将
all.var_color[j]
其视为一个数组,但它是一个对象。
要获得原色,请将内部循环 ( for (let j in all)
) 替换为一个简单的测试:
if(all.var_color) {
let variantColor = all.var_color.color.primary;
console.log(variantColor);
}
var data = {
"products": [
{
"_id": "000",
"name": "Name 1",
"description": "Long description 1"
},
{
"_id": "001",
"name": "Name 2",
"description": "Long description 2",
"var_color": {
"_id": "12341",
"color": {
"primary": "pink",
"secondary": "penk"
}
}
},
{
"_id": "002",
"name": "Name 3",
"description": "Long description 3"
},
{
"_id": "003",
"name": "Name 4",
"description": "Long description 4",
"var_color": {
"_id": "12342",
"color": {
"primary": "red",
"secondary": "rid"
}
}
}
],
"categories": []
};
for (let i in data.products) {
let all = data.products[i];
let name = all.name;
let description = all.description;
console.log(name);
console.log(description);
if(all.var_color) {
let variantColor = all.var_color.color.primary;
console.log(variantColor);
}
}
推荐阅读
- r - 将因子转换为二进制不对称变量类型
- api - jFrog Artifactory 仅标记文件夹内的文件
- javascript - 通过单击按钮关闭检查我何时关闭 kendoWindow
- r - 如何将列表值列拆分为多列?
- activemq-artemis - 如何更改 ActiveMQ Artemis 中的 minLargeMessageSize?
- python - 以公式为值的 Python Pandas eval
- python - 无法将 keras 模型转换为 tensorflow:类型对象“密集”没有属性“from_config”
- javascript - 使用可变比例时使用 React 和 D3 分离关注点
- php - SagePay 返回成功但失败 INVALID_SIGNATURE PPro
- c - c语言循环后矩阵乘法错误