如何在React Native中从数组中获取特定值

时间:2019-06-17 11:49:19

标签: javascript reactjs react-native ecmascript-6

我正在尝试仅获取“ _workAgent”的值,其中_activityStatus“ ==” I“。

请查看我的代码,如下所述,我正在获得价值。

[“ 501”]

0:“ 501”

长度:1

而我只需要在一个变量中获取501值

     "workAgent_ID": [
              {
                "_activityName": "FXL_ACT1",
                "_activityStatus": "I",
                "_userName": "tecnotree",
                "_maxHoldTime": "60",
                "_workAgent": "501"
              },
              {
                "_activityName": "FXL_ACT2",
                "_activityStatus": "N",
                "_userName": null,
                "_maxHoldTime": "120",
                "_workAgent": "510"
              }

   const currentStepPosition = workAgent_ID.filter((item) => {
        return item._activityStatus === "I"
          });
       const workAgentID = currentStepPosition.map(currentStepPosition => {
        return currentStepPosition._workAgent;
           });

2 个答案:

答案 0 :(得分:0)

map返回数组的新集合。 就您而言,我认为您不需要映射currentStepPosition。 只需执行以下代码:

const currentStepPosition = workAgent_ID.filter((item) => {
        return item._activityStatus === "I"
          })[0];

const workAgentID  = currentStepPosition._workAgent

答案 1 :(得分:0)

这是您可以采用的一种简单方法,如果未找到对象,则此逻辑不会失败。因此,它在两种情况下都适用。

var values =    { "workAgent_ID": [
              {
                "_activityName": "FXL_ACT1",
                "_activityStatus": "I",
                "_userName": "tecnotree",
                "_maxHoldTime": "60",
                "_workAgent": "501"
              },
              {
                "_activityName": "FXL_ACT2",
                "_activityStatus": "N",
                "_userName": null,
                "_maxHoldTime": "120",
                "_workAgent": "510"
              }]}


const index = values.workAgent_ID.findIndex(item => item._activityStatus === "I")
if(index > -1){
  console.log("Result object", values.workAgent_ID[index])
}