【问题标题】:Use a keys value to find a matching key in another object and replace with its valueUse a keys value to find a matching key in another object and replace with its value
【发布时间】:2022-12-01 19:20:34
【问题描述】:

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"
          }
        }
      }
    }
    
let data2 = [
      {
        "name": "Surname",
        "displayName": "Surname",
        "value": "Bush",
        "dataType": "STRING",
        "displayLevel1": "Main",
        "displayLevel2": "Personal Details",
        "displayLevel3": ""
      }
    ]

data2is the original data source in this scenario.

So, indata2I want to use the key name use its value, in this example its "surname". Then indata1find the value of "surname", in this example that's "smith". I then want to use "smith" as the new value for the value key back indata2- which replaces "Bush" in this example.

End result being:

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

Any help would be appreciated here! thanks

【问题讨论】:

  • Are you expecting this - data2.value = data1.fields[data2.displayLevel1][data2.displayLevel2][data2.name] ??
  • no, the expectation is the example shown above. let data2 = [ { "name": "Surname", "displayName": "Surname", "value": "Smith", "dataType": "STRING", "displayLevel1": "Main", "displayLevel2": "Personal Details", "displayLevel3": "" } ]
  • the only value that has changed is the value of the value key in data2

标签: javascript arrays object mapping


【解决方案1】:

A very basic way of doing it would be

// get the value of key "Name" in data 2
const nameVal = data2[0]['name'] 

// once you have the value you can get the surname from data 1 obj 
const simplifiedObj = data1['fields']['Main']['Personal Details']
const surname = simplifiedObj[nameVal]

//finally you can assign your data2 (which is an array of objects, and not an object itself) the new value
data2[0]['value'] = surname

【讨论】:

  • Thanks. The nested objects may be different e.g ['fieldsOne']['another']['Another name]
猜你喜欢
  • 2022-12-02
  • 2022-12-02
  • 2022-10-25
  • 2023-04-01
  • 1970-01-01
  • 2022-12-02
  • 1970-01-01
  • 2022-12-27
  • 1970-01-01
相关资源
最近更新 更多