Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find all the string values and the corresponding keys

I am trying to find all the string values from the array of objects and then format the keys.

//it works for a single object and string
// need help to implement an array of Object and string
function getKeyByValue(object, value) {
  return Object.keys(object).find((key) => object[key] === value);
}

const data = [
  {
    AddressFlag: true,
    BaseMasterTable: "DIMCUSTOMER",
     ContextName: "Kunden",
    DefaultOutputFormats: null,
    HouseHoldColumn: null,
    I18N: [],
    ID: 5,
    PrimaryKey: "CustomerKey",
    
  }
];

const mapper = data.map((item) => {
  const values = Object.values(item).filter((item) => typeof item === "string");
  console.log(values);
// problem here;
//it's now taking a single object and a single string
// how can I take an array of objects and strings as parameters here
  console.log(getKeyByValue(data[0], values[1]));
});

And finally output in this format

[
{fieldname: 'ContextName'},
{fieldName: 'PrimaryKey'},
{fieldName: 'BaseMasterTable'}
]
like image 857
Mamunur Rashid Avatar asked Dec 04 '25 14:12

Mamunur Rashid


1 Answers

You can try this approach with Object.entries and map together. And flatMap to group all string data into a single array.

const data = [{
  AddressFlag: true,
  BaseMasterTable: "DIMCUSTOMER",
  ContextName: "Kunden",
  DefaultOutputFormats: null,
  HouseHoldColumn: null,
  I18N: [],
  ID: 5,
  PrimaryKey: "CustomerKey",
}];

const mapper = data.flatMap((item) => {
  const result = Object.entries(item).filter(([key, value]) => typeof value === "string").map(([key, value]) => ({
    fieldname: key
  }));
  return result
});

console.log(mapper)
like image 94
Nick Vu Avatar answered Dec 07 '25 02:12

Nick Vu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!