Home > Net >  how to specify certain field which is inside array in restapi
how to specify certain field which is inside array in restapi

Time:01-19

I have an api link https://apilink.com?_fields=id,name,images which gives me the following format

[
  {
    "id": 229210,
    "name": "Basic Electrical Knowledge",
    "images": [
      {
        "id": 229211,
        "date_created": "2023-01-13T18:34:39",
        "date_created_gmt": "2023-01-13T07:34:39",
        "date_modified": "2023-01-13T18:34:39",
        "date_modified_gmt": "2023-01-13T07:34:39",
        "src": "https://sampleSite.in/wp-content/uploads/2023/01/SomeUrlSource.jpg",
        "name": "Basic Electrical Knowledge",
        "alt": ""
      }
    ]
  }
]

I want to access only src from images[]. How do I retrieve this from the link. When clicking the link I want to display this:

[
  {
    "id": 229210,
    "name": "Basic Electrical Knowledge",
    "src": "https://sampleSite.in/wp-content/uploads/2023/01/SomeUrlSource.jpg"
  }
]

How do I do this?

I tried to solve this by providing this parameters: https://apilink.com?_fields=id,name,images=src

CodePudding user response:

You can achieve this by making a GET request to the API link and then using a library such as JSON.parse() to parse the response and extract the necessary data. After that, you can use a for loop to iterate over the 'images' array in the response and extract the 'src' key from each object in the array. Finally, you can construct a new object with the desired format and return it.

fetch(https://apilink.com?_fields=id,name,images)
  .then(response => response.json())
  .then(data => {
    let newData = []
    data.forEach(item => {
        let newItem = {
          id: item.id,
          name: item.name,
          src: item.images[0].src
        }
        newData.push(newItem)
    });
    return newData;
  })
  .then(newData => {
    console.log(newData);
  });

Note that this code snippet is simplified and doesn't handle errors, it's only serve as an example of how you could do it.

CodePudding user response:

Assuming that you can't make server-side changes, implement a little script, and want the result just manipulating the URI the response is no.

The URI is referring to a resource in the server, the _fields seem like a projection to make to the attributes of the desired resource.

In this case, you are trying to make a transformation on the resource given by the server through. If the server does not implement such functionality you must do it by yourself.

You want to transform the attribute images that has type [Object] to a String. A code snippet like the answered by @RASIKA EKANAYAKA would fit your requirement.

  • Related