简体   繁体   中英

Get specific value from array of objects [{“key”:“value”}, {“key”:“value”}]

I'm trying to interact with the API of processmaker. I have made a simple form to authenticate and get the authorization token, which is needed to interact with the rest of the API.

I am able to use the token to output a json response of created projects after login. The response is an array of objects.

I need to get the prj_uid for an api request so I want to extract these, but I've had little luck using map.

How can I iterate over the response and get prj_name and prj_uid for each of the objects in the array?

import React, { useState, useEffect } from "react";
//import ResponsiveEmbed from "react-responsive-embed";

const Tasks = ({ loggedIn }) => {
  const [hasError, setErrors] = useState(false);
  const [projects, setProjects] = useState([]);
  const url = "http://127.0.0.1:8080/api/1.0/workflow/project";

  useEffect(() => {
    let access_token = sessionStorage.getItem("access_token");

    async function fetchData() {
      const response = await fetch(url, {
        method: "GET",
        withCredentials: true,
        timeout: 1000,
        headers: {
          Authorization: "Bearer " + access_token
        }
      });
      response
        .json()
        .then(response => setProjects(response))
        .catch(err => setErrors(err));
    }
    fetchData();
  }, [loggedIn]);


  console.log(JSON.stringify(loggedIn) + " logged in, displaying projects");
  console.log(projects + " projects");
  if (!loggedIn) {
    return <h1>Error</h1>;
  } else {
    return (
      <>
        <p>Login success!</p>
        <h2>Projects:</h2>
        <span>{JSON.stringify(projects)}</span>
        <div>Has error: {JSON.stringify(hasError)}</div>
      </>
    );
  }
};
export default Tasks;

Stringified Response:

[  
   {  
      "prj_uid":"1755373775d5279d1a10f40013775485",
      "prj_name":"BPMN Process",
      "prj_description":"This is a processmaker BPMN Project",
      "prj_category":"8084532045d5161470c0de9018488984",
      "prj_type":"bpmn",
      "prj_create_date":"2019-08-13 08:50:25",
      "prj_update_date":"2019-08-13 09:04:16",
      "prj_status":"ACTIVE"
   },
   {  
      "prj_uid":"7459038845d529f685d84d5067570882",
      "prj_name":"Purchase Request",
      "prj_description":"",
      "prj_category":"2284311685392d2e70f52e7010691725",
      "prj_type":"bpmn",
      "prj_create_date":"2019-08-13 11:30:48",
      "prj_update_date":"2019-08-13 12:20:05",
      "prj_status":"ACTIVE"
   }
]

Array.map() is your answer- you had it right. its as simple as:

let mappedObject = result.map( el => ({ prj_name, prj_uid }) );

el is every element in the array, and we construct the new array with an object containing only prj_name and prj_uid . Because el alraeady has those properties with those names, we do not need to write { prj_name: el.prj_name } when we construct the new object, it is implied and will do the trick with only the property names there.

mappedObject will now hold an array of objects consists only of the asked properties.

You might wanna read more about map to understand it better- Array.map()

If loggedIn is the json object, then you can do this:

const uidNameArr = loggedIn.map((item) => { // returns an array of arrays with the values you want.
  return [item.prj_uid, item.prj_name]
})

uidNameArr.forEach(([uid,name]) => {
 console.log(`${name} has a uid of ${uid}`)
})

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