在数组[1]中获取比较数组[2]的值.value = array [2] .key

时间:2018-05-09 04:45:27

标签: javascript arrays json

我有一个样本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

我花了很多时间来做这件事,但我不善于处理数组,

有没有办法得到结果?

1 个答案:

答案 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_ID3,与你在问题中提到的相反。