Use a keys value to find a matching key in another object and replace with its value

Advertisements

I have a nested object and an array of objects (http://jsfiddle.net/9phkbgqe/):

let data1 = 
    {
      "fields": {
        "Main": {
          "Personal Details": {
            "Surname": "Smith",
            "Forename1": "John",
            "Nickname": "Johny",
            "Gender": "Male",
            "Date_of_Birth": "05/04/1979",
            "Marital_Status": "Divorced"
          },
          "More Details": {
            "Injury": "Hand",
          }
        }
      }
    }
    
let data2 = [
      {
        "name": "Surname",
        "displayName": "Surname",
        "value": "Bush",
        "dataType": "STRING",
        "displayLevel1": "Main",
        "displayLevel2": "Personal Details",
        "displayLevel3": ""
      },
      {
        "name": "Injury",
        "displayName": "Injury",
        "value": "Arm",
        "dataType": "STRING",
        "displayLevel1": "Main",
        "displayLevel2": "More Details",
        "displayLevel3": ""
      }
    ]

data2 is the original data source in this scenario.

So, in data2 I want to use the key name use its value, in this example its "Surname". Then in data1 find the value of "Injury", in this example that’s "smith". I then want to use "smith" as the new value for the value key back in data2 – which replaces "Bush" in this example.

Another example added
So, in data2 I want to use the key name use its value, in this example its "Injury". Then in data1 find the value of "Injury", in this example that’s "Hand". I then want to use "Hand" as the new value for the value key back in data2 – which replaces "Arm" in this example.

End result being:

let data2 = [
      {
        "name": "Surname",
        "displayName": "Surname",
        "value": "Smith",
        "dataType": "STRING",
        "displayLevel1": "Main",
        "displayLevel2": "Personal Details",
        "displayLevel3": ""
      },
      {
        "name": "Injury",
        "displayName": "Injury",
        "value": "Hand",
        "dataType": "STRING",
        "displayLevel1": "Main",
        "displayLevel2": "More Details",
        "displayLevel3": ""
      }
    ]

Any help would be appreciated here! thanks

>Solution :

const newData = data2.map((data) => {
  const val = ''
  if (data.displayLevel3) {
    return {
      ...data,
      value: data1.fields[data.displayLevel1][data.displayLevel2][data.displayLevel3][data.name]
    }
  }
  if (data.displayLevel2) {
    return {
      ...data,
      value: data1.fields[data.displayLevel1][data.displayLevel2][data.name]
    }
  }
  if (data.displayLevel1) {
    return {
      ...data,
      value: data1.fields[data.displayLevel1][data.name]
    }
  }
  return {
    ...data,
    value: data1.fields[data.name]
  }
})

Leave a Reply Cancel reply