简体   繁体   English

从具有动态 ID 的嵌套对象中获取值 - javascript

[英]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.我正在从 SlackAPI(块元素)接收有效负载,但我无法理解哦,我如何从它获取数据,因为 ids 和 order 总是在变化。 I want to get protection_fee.value, legal_fee.value and repayment_date.selected_date我想得到 protection_fee.value、legal_fee.value 和 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.我尝试了 Object.keys 但显然我因为订单更改而失败了。

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;

I would suggest creating a function like findProperty() that will find the relevant object in the payload.我建议创建一个像findProperty()这样的函数,它将在有效负载中找到相关对象。

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.我们会在payload.state.values对象上调用Object.entries() ,然后在入口键/值对上使用Array.find()来查找具有所需属性的对象。

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; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM