gpt4 book ai didi

javascript - 迭代嵌套 JSON

转载 作者:行者123 更新时间:2023-12-03 04:57:57 25 4
gpt4 key购买 nike

我有嵌套对象,例如

{
"root": {
"company": [{
"id": "Google",
"contact": [{
"field": "name",
"value": "Larry Page"
}, {
"field": "flag",
"value": ""
}, {
"field": "initial",
"value": "LP"
}
]
}, {
"id": "Snap",
"contact": [{
"field": "name",
"value": "Evan Spiegel"
}, {
"field": "flag",
"value": "true"
}, {
"field": "initial",
"value": "ES"
}
]
}, {
"id": "Airbnb",
"contact": [{
"field": "name",
"value": "Brian Chesky"
}, {
"field": "flag",
"value": ""
}, {
"field": "initial",
"value": "BC"
}
]
}
]
}
}

我需要根据标志值创建 2 个单独的列表 - 一个用于 flag = "",另一个用于 flag = true

预期结果是 2 个列表:

var flagisTrue = {ES}
var flagisEmpty = [{"name":"Larry Page", "initial": "LP"}, {"name":"Brian Chesky", "initial": "BC"}]

其中 flagisTrue 仅包含首字母,而 flagisEmpty 包含名称和首字母。

如何在 JavaScript 中使用此结构?

最佳答案

试试这个。希望它会有所帮助。

var object = {
"root" : {
"company" : [{
"id" : "Google",
"contact" : [{
"field" : "name",
"value" : "Larry Page"
}, {
"field" : "flag",
"value" : ""
}, {
"field" : "initial",
"value" : "LP"
}
]
}, {
"id" : "Snap",
"contact" : [{
"field" : "name",
"value" : "Evan Spiegel"
}, {
"field" : "flag",
"value" : "true"
}, {
"field" : "initial",
"value" : "ES"
}
]
}, {
"id" : "Airbnb",
"contact" : [{
"field" : "name",
"value" : "Brian Chesky"
}, {
"field" : "flag",
"value" : ""
}, {
"field" : "initial",
"value" : "BC"
}
]
}
]
}
}

var flagisTrue = [], flagisEmpty = [];
for (var i = 0; i < object.root.company.length; i++) {
var contact = object.root.company[i].contact;
var result = {};
for (var j = 0; j < contact.length; j++)
result[contact[j].field] = contact[j].value;

if (result["flag"])
flagisTrue.push({
name : result["name"],
initial : result["initial"]
});
else
flagisEmpty.push({
name : result["name"],
initial : result["initial"]
});
}

console.log(flagisEmpty);
console.log(flagisTrue);

关于javascript - 迭代嵌套 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42358505/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com