我有一个样本json Array1
:
[
{
"name": "Primary Category",
"value": [
{
"value": "Fracture",
"Diagnosis_Code": ["DIAG003"],
"name": "Primary Category",
"FK_Diagnosis_Content_ID": 3,
"FK_Diagnosis_Category_ID": 1
},
{
"value": "Osteoarthritis",
"Diagnosis_Code": ["DIAG001"],
"name": "Primary Category",
"FK_Diagnosis_Content_ID": 1,
"FK_Diagnosis_Category_ID": 1
},
{
"value": "Osteonecrosis",
"Diagnosis_Code": ["DIAG002", "DIAG004"],
"name": "Primary Category",
"FK_Diagnosis_Content_ID": 2,
"FK_Diagnosis_Category_ID": 1
},
]
},
{
"name": "Anatomy",
"value": [
{
"value": "Hip",
"Diagnosis_Code": ["DIAG001"],
"name": "Anatomy",
"FK_Diagnosis_Content_ID": 4,
"FK_Diagnosis_Category_ID": 2
},
{
"value": "Pelvis",
"Diagnosis_Code": ["DIAG002", "DIAG003", "DIAG004"],
"name": "Anatomy",
"FK_Diagnosis_Content_ID": 6,
"FK_Diagnosis_Category_ID": 2
}
]
}
]
我有第二个样本json Array2
:
[ 'Primary Category': 'Fracture', 'Anatomy': 'Pelvis' ]
正如您在Array2
上看到的那样,有一些价值Fracture and Pelvis
,我希望Array1.FK_Diagnosis_Content_ID
取决于Array2 value
因此取决于Array2
我会得到一个结果:[2,6]因为Fracture
中的Array1
FK_Diagnosis_Content_ID
= 2且Pelvis
位于Array1
FK_Diagnosis_Content_ID
有{{1}} = 6
我花了很多时间来做这件事,但我不善于处理数组,
有没有办法得到结果?
答案 0 :(得分:1)
我已将Array2
更正为有效数组。
您可以在第一个数组上使用Array#reduce
,并在每次迭代中检查项目的值是否包含在Array2
中:
const Array1 = [{"name":"Primary Category","value":[{"value":"Fracture","Diagnosis_Code":["DIAG003"],"name":"Primary Category","FK_Diagnosis_Content_ID":3,"FK_Diagnosis_Category_ID":1},{"value":"Osteoarthritis","Diagnosis_Code":["DIAG001"],"name":"Primary Category","FK_Diagnosis_Content_ID":1,"FK_Diagnosis_Category_ID":1},{"value":"Osteonecrosis","Diagnosis_Code":["DIAG002","DIAG004"],"name":"Primary Category","FK_Diagnosis_Content_ID":2,"FK_Diagnosis_Category_ID":1}]},{"name":"Anatomy","value":[{"value":"Hip","Diagnosis_Code":["DIAG001"],"name":"Anatomy","FK_Diagnosis_Content_ID":4,"FK_Diagnosis_Category_ID":2},{"value":"Pelvis","Diagnosis_Code":["DIAG002","DIAG003","DIAG004"],"name":"Anatomy","FK_Diagnosis_Content_ID":6,"FK_Diagnosis_Category_ID":2}]}];
const Array2 = ['Fracture', 'Pelvis'];
const result = Array1.reduce((acc, item) => {
item.value.forEach(i => {
if (Array2.includes(i.value)) {
acc.push(i.FK_Diagnosis_Content_ID);
}
})
return acc;
}, []);
console.log(result);
顺便说一句,断裂的
FK_Diagnosis_Content_ID
是3
,与你在问题中提到的相反。