Home > Blockchain >  Create new array of objects based off nested value using React
Create new array of objects based off nested value using React

Time:11-22

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

CodePudding user response:

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