API return values based on certain criteria

Tags: , ,



I am working on an API, and I want to return values based on some input I receive. For example, here is a body sample input

{
 "fields": ["account", "id"]
}

Based on the fields array, I want my API to return only those values. Here is an example of the API implementation

...
const {fields} = req.body
const result = makeDataConversion(data)
      const objKeys = result.map((i) => Object.keys(i)) // returns the keys from the arr of object of the result variable

// I am comparing the values in the fields array with the keys gotten from objKeys variable
      if (fields) {
        fields.forEach((items) => {
          objKeys.forEach((item) => {
            if (items.indexOf(item) > -1) {
              const s = result.filter(item => {}) // stuck here
              res.json({ s })
            }
          })
        })
      }
...

So the part where I indicate stuck here I want to loop through the result array of objects and return only the properties that match the values gotten from the field’s array.

Here is a typical API Response

status: true
message: "Data retrieved successfully"
data: [
 { 
 "account": "john doe",
 "date_registered": "10/10/1994",
 "amount": "50000",
 "isActive": "false"
 "id": "34"
 }
]

So my final API Response should be

status: true
message: "Data retrieved successfully"
data: [{"account": "john doe", "id": "34"}]

How do I go about this please.

Thank you

Answer

const apiResponse = { 
status: true,
message: "Data retrieved successfully",
data: [
 { 
 "account": "john doe",
 "date_registered": "10/10/1994",
 "amount": "50000",
 "isActive": "false",
 "id": "34"
 },
 {
"account": "john doe 2",
 "date_registered": "10/10/1994",
 "amount": "50000",
 "isActive": "false",
 "id": "35"
  }
]
};

const fieldsInput = {
 "fields": ["account", "id"]
};

const getFinalResult = (response) => {
    
    const data = response.data.map(item  => {
        const result = {};
        fieldsInput.fields.forEach(field => {
            result[field] = item[field];
        })
        return result;
   });

  return {
    ...response,
    data
  }
};

const finalResult = getFinalResult(apiResponse);

console.log(finalResult);

Just doing a .map() over your response and inside that map just iterate over your fields and returned the mapped result based on those fields.



Source: stackoverflow