Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :(")
    });
}, []);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 :(")
    });
}, []);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading