我可以从json中获取另一个对象的key值吗?我该怎么做?使用数组过滤器还是for循环?
我尝试使用数组过滤器,但它只返回整个json对象
这是我的示例JSON:
[
{
"type":1,
"key": "123abc",
"data": {
"access": "123456"
"data": {
"dataValue": [
{
"@attr": {
"@key": "Fire"
},
"@value": "Flame"
},
{
"@attr": {
"@key": "Water"
},
"@value": "Liquid"
},
{
"@attr": {
"@key": "Earth"
},
"@value": "Stone"
}
]
}
}
}
]
我想要的是通过从“ @key”中搜索“水”来从@value中获取“液体”值
输出: 液体
感谢您的帮助。
答案 0 :(得分:1)
您可以按以下方式从已解析的对象中使用过滤器:
Option Explicit
Sub CopySheetToAnotherWorkbook()
Dim wbk1 As Workbook: Set wbk1 = ActiveWorkbook
Dim wbk2 As Workbook
Dim Report As Worksheet: Set Report = ActiveWorkbook.Worksheets("Report")
Dim CopySht As Worksheet
With Report
.Cells.Copy
End With
Set wbk2 = Workbooks.Add
wbk2.SaveAs ThisWorkbook.Path & "\" & "workbooktosend.xlsx"
Set CopySht = wbk2.Sheets("Sheet1")
With Cells
.PasteSpecial (xlPasteValues)
.PasteSpecial (xlPasteFormats)
End With
ActiveWindow.DisplayGridlines = False
ActiveWindow.Zoom = 80
End Sub
Sub AddFileToMail()
Dim OutLookApp As Outlook.Application
Dim myMail As Outlook.MailItem
Dim sourcefile As String
Set OutLookApp = New Outlook.Application
Set myMail = OutLookApp.CreateItem(olMailItem)
myMail.Attachments.Add ThisWorkbook.Path & "\" & "workbooktosend.xlsx"
End Sub
答案 1 :(得分:-1)
我将简化一点,并说我们正在研究dataValue
数组。
// For each item in dataValue, check the key.
// If it equals 'Water', return the value.
for (let i = 0; i < dataValue.length; i++) {
if (value['@attr']['@key'] === 'Water') {
return value['@value'];
}
}
答案 2 :(得分:-1)
这将获取对象的值
var json = JSON.parse(`[{"type":1,"key":"123abc","data":{"access":"123456","data":{"dataValue":[{"@attr":{"@key":"Fire"},"@value":"Flame"},{"@attr":{"@key":"Water"},"@value":"Liquid"},{"@attr":{"@key":"Earth"},"@value":"Stone"}]}}}]`);
function getValue(dataValues, key) {
return dataValues.find(function(item) {
return item["@attr"]["@key"] === key;
});
}
var dataValues = json[0].data.data.dataValue;
var dataValue = getValue(dataValues, "Water");
console.log(dataValue["@value"]);
这将为您提供每个对象的值
var json = JSON.parse(`[{"type":1,"key":"123abc","data":{"access":"123456","data":{"dataValue":[{"@attr":{"@key":"Fire"},"@value":"Flame"},{"@attr":{"@key":"Water"},"@value":"Liquid"},{"@attr":{"@key":"Earth"},"@value":"Stone"}]}}}]`);
function getValue(dataValues, key) {
return dataValues.find(function(item) {
return item["@attr"]["@key"] === key;
});
}
console.log(json.map(function(jsonObject) {
return getValue(jsonObject.data.data.dataValue, "Water")["@value"];
}));