简体   繁体   中英

Create new array of objects based off nested value using React

I'm returning an array of objects from an API and I would like to create a new variable in the useEffect with units that are set to isActive . Not sure on the best way to do it.

[
  {
    "fields": {
      "assetKey": {
        "en-US": "YMW-24"
      },
      "isActive": {
        "en-US": false
      }
    }
  },
  {
    "fields": {
      "assetKey": {
        "en-US": "YMW-25"
      },
      "isActive": {
        "en-US": true
      }
    }
  },
  {
    "fields": {
      "assetKey": {
        "en-US": "YMW-21"
      },
      "isActive": {
        "en-US": false
      }
    }
  }
]

useEffect with promise

useEffect(() => {
    const referenceEntityIDs = unitsField.map((i) => i.sys.id);
    Promise.all(referenceEntityIDs.map((id) => sdk.space.getEntry(id)))
    .then((data) => {
        // Getting all units  
        const getAllUnits = data.map((unit) => unit.fields.assetKey["en-US"]);
        setAllUnits(getAllUnits);

        // TODO Return units that are set to active in a variable

    })
    .catch(() => {
        console.log("Units fail :(")
    });
}, []);
useEffect(() => {
    const referenceEntityIDs = unitsField.map((i) => i.sys.id);
    Promise.all(referenceEntityIDs.map((id) => sdk.space.getEntry(id)))
    .then((data) => {
        // Getting all units  
        const getAllUnits = data.map((unit) => unit.fields.assetKey["en-US"]);
        setAllUnits(getAllUnits);

        // TODO Return units that are set to active in a variable
        const active = getAllUnits.filter((unit) => unit.fields.isActive["en-US"]);

    })
    .catch(() => {
        console.log("Units fail :(")
    });
}, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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