Home > Back-end >  Get Value from an Array with Objects that have Name and Value
Get Value from an Array with Objects that have Name and Value

Time:07-11

I am receiving a payment Webhook that has a CallBackmetadata with Item as an array. This array has objects with Name and Value in them and I have never seen such a thing before. When I console.log(CallbackMetadata) I get this array

[
  { Name: 'Amount', Value: 1 },
  { Name: 'MpesaReceiptNumber', Value: 'QGB39WES55' },
  { Name: 'Balance' },
  { Name: 'TransactionDate', Value: 20220711124027 },
  { Name: 'PhoneNumber', Value: 254704407239 }
]

I have 4 vars, Amount, ReceiptNo, PhoneNumber and Transaction Date that I want to populate with the values in the array.

How do I go about it? My full Code

const express = require("express");
const prettyjson = require("prettyjson");
const Router = express.Router();

Router.post("/stk-webhook", async (req, res) => {
  let CallbackMetadata;
  let ResultCode;
  let Amount;
  let ReceiptNumber;
  let TransactionDate;
  let PhoneNumber;

  console.log("_____________RECEIVED_MPESA_WEBHOOK________");
  console.log(prettyjson.render(req.body));
  try {
    ResultCode = req.body.Body.stkCallback.ResultCode;
    CallbackMetadata = req.body.Body.stkCallback.CallbackMetadata.Item;
    if (ResultCode === 0) {
      //  populate vars with their values
    } else {
      console.log("You cancelled transaction");
      res.status(400).json({ message: "you cancelled transaction" });
    }
    console.log(mpesaResponseObject);
  } catch (error) {
    console.log(error);
  }
});
module.exports = Router;

CodePudding user response:

I'd create a simple mapping function where you create an object from the array values. Then, you can simply use object destructering to access the desired properties. Something like this:

const callbackMetadata = [
  { Name: 'Amount', Value: 1 },
  { Name: 'MpesaReceiptNumber', Value: 'QGB39WES55' },
  { Name: 'Balance' },
  { Name: 'TransactionDate', Value: 20220711124027 },
  { Name: 'PhoneNumber', Value: 254704407239 }
]


function mapMetadata(metadata) {      
  return metadata.reduce((result, entry) => { 
      result[entry.Name] = entry.Value;
      return result;
  }, {});
}

const mappedResult = mapMetadata(callbackMetadata);
let {Amount, MpesaReceiptNumber, TransactionDate, PhoneNumber} = mappedResult;

console.log("Amount", Amount);
console.log("MpesaReceiptNumber", MpesaReceiptNumber);
console.log("TransactionDate", TransactionDate);
console.log("PhoneNumber", PhoneNumber);

  • Related