Search key and return value in nested object

前端 未结 4 846
盖世英雄少女心
盖世英雄少女心 2021-01-28 17:02

Lets say my object looks like the below. Its a mix of different arrays and parents, no hierarchical order. e.g.

\"person\": {
\"id\": 12345,
\"name\": \"John Doe         


        
4条回答
  •  無奈伤痛
    2021-01-28 17:26

    You will need a recursive function. For explanation please check the comments

    let person = {
      "id": 12345,
      "name": "John Doe",
      "emergencyContacts": [{
          "name": "Jane Doe",
          "phone": "888-555-1212",
          "relationship": "spouse",
          "moreDetails": {
            "id": 12345,
            "phones": {},
            "home": "800-123-4567",
            "mobile": "877-123-1234"
          }
        },
        {
          "name": "Justin Doe",
          "phone": "877-123-1212",
          "relationship": "parent",
          "mobile": "877-123-1234"
        }
      ],
      "workContacts": [{
          "name": "Jane Doe",
          "phone": "888-555-1212",
          "relationship": "spouse",
          "moreworkDetails": {
            "id": 12345,
            "phones": {},
            "home": "800-123-4567",
            "mobile": "877-123-1236"
          }
        },
        {
          "name": "Justin Doe",
          "phone": "877-123-1212",
          "relationship": "parent",
          "mobile": "877-123-1235"
        }
      ]
    }
    let arrys = [];
    
    //iterate the object 
    function recursive(obj, key) {
      //iterate the object
      for (let keys in obj) {
        // check if the key name is same as the desired one
        if (keys === key) {
          // then push the value to an array
          arrys.push(obj[keys])
    
        } else {
          // if the value of a key is an array & if it is not empty
          if (Array.isArray(obj[keys]) && obj[keys].length > 0) {
            // iterate the array. in each iteration you will get the object
            // example emergencyContacts. In each iteration 
            // call the same function with new data 
            obj[keys].forEach(function(item) {
              // pass that object to the same function
              recursive(item, key)
            })
    
          }
          // if the value is an object then again call the same function 
          else if (typeof obj[keys] === 'object') {
            recursive(obj[keys], key)
          }
        }
      }
    }
    
    recursive(person, 'mobile');
    //create object from the array
    let newObj = {}
    for (let m = 0; m < arrys.length; m++) {
      newObj[m] = arrys[m]
    
    }
    console.log(newObj)

提交回复
热议问题