Search code examples
javascriptslack-apislack-block-kit

Get values from nested object with dynamic ids - javascript


I'm recieving a payload from SlackAPI (block elements) and I can't get my head around oh how do I get data from it as ids and order always change. I want to get protection_fee.value, legal_fee.value and repayment_date.selected_date

"state": {
"values": {
  "CjV": {
    "protection_fee": {
      "type": "plain_text_input",
      "value": "111"
    }
  },
  "36tAM": {
    "legal_fee": {
      "type": "plain_text_input",
      "value": "111"
    }
  },
  "oH8": {
    "repayment_date": {
      "type": "datepicker",
      "selected_date": "1990-04-18"
    }
  }
}

},

I tried Object.keys but obviously I failed as order changes.

current code:

      const payload = JSON.parse(body);
      const state = payload.state.values;
      const first = Object.keys(state)[0];
      const second = Object.keys(state)[1];
      const repaymentDate = state[first].protection_fee.value;
      const protectionFee = state[second].legal_fee.value;

Solution

  • I would suggest creating a function like findProperty() that will find the relevant object in the payload.

    We'd call Object.entries() on the payload.state.values object and then using Array.find() on the entry key/value pairs to find an object with the desired property.

    Once we have the property we can return it.

    let payload = { "state": { "values": { "CjV": { "protection_fee": { "type": "plain_text_input", "value": "111" } }, "36tAM": { "legal_fee": { "type": "plain_text_input", "value": "111" } }, "oH8": { "repayment_date": { "type": "datepicker", "selected_date": "1990-04-18" } } } } }
    
    function findProperty(obj, key) {
        const [, value] = Object.entries(obj).find(([k,v]) => v[key]);
        return value[key];
    }
    
    console.log('legal_fee:', findProperty(payload.state.values, 'legal_fee').value)
    console.log('protection_fee:', findProperty(payload.state.values, 'protection_fee').value)
        
    .as-console-wrapper { max-height: 100% !important; }