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'}
]
CodePudding user response:
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)
CodePudding user response:
You can use flatMap and Object.entries() for this. Pretty simple:
const data = [
{
AddressFlag: true,
BaseMasterTable: "DIMCUSTOMER",
ContextName: "Kunden",
DefaultOutputFormats: null,
HouseHoldColumn: null,
I18N: [],
ID: 5,
PrimaryKey: "CustomerKey",
},
{
AddressFlag: true,
BaseMasterTable: "DIMCUSTOMER",
ContextName: "Kunden",
DefaultOutputFormats: null,
HouseHoldColumn: null,
I18N: [],
ID: 5,
PrimaryKey: "CustomerKey",
}
];
const result = data.flatMap(element => {
return Object.entries(element)
.filter(([,value]) => typeof value === "string")
.map(([key]) => ({fieldName: key}));
});
console.log(result)
This will duplicate keys, you can then filter if you need to.
CodePudding user response:
This answer is almost the same approach as provided answers. Only difference is it is one loop less. I'm using flatMap
here instead of filter
& map
. Something like this:-
const data = [{AddressFlag: true,BaseMasterTable: "DIMCUSTOMER",ContextName: "Kunden", DefaultOutputFormats: null, HouseHoldColumn: null, I18N: [], ID: 5, PrimaryKey: "CustomerKey", } ];
const result = data.flatMap(e=>Object.entries(e).flatMap(([fieldName,v])=>typeof v==='string' ? ({fieldName}) : []));
console.log(result);
CodePudding user response:
Each object of array is iterated by .flatMap()
. On each iteration the current object is converted into an array of pairs by Object.entries()
data.flatMap(obj => Object.entries(obj)
// [["AddressFlag", true], ["BaseMasterTable", "DIMCUSTOMER"], [...], ...]
Next, .flatMap()
is used again, but this time as a filter. Since .flatMap()
flattens it's returns by a level we can apply a ternary or if
/else if
/else
statement with a empty array ([]
) as the else
or last part of a ternary. Doing so will cleanly return nothing (instead of the usual empty (""
)). This technique is especially useful because you can return anything -- in the example, the condition is checking each pair second element (pair[1]
which is originally the value) and if it's the given type (in the example is "string"
) the first element of the pair is returned as the value of an object (pair[0]
which is originally the key). If it isn't the given type an empty array is returned.
data.flatMap(obj => Object.entries(obj).flatMap(pair =>
typeof pair[1] === "string" ? {"fieldName": pair[0]} : []))
// is "DIMCUSTOMER" a string ? return {"fieldName": "BaseMasterTable"} OR []
Details are commented in example
const data = [{
AddressFlag: true,
BaseMasterTable: "DIMCUSTOMER",
ContextName: "Kunden",
DefaultOutputFormats: null,
HouseHoldColumn: null,
I18N: [],
ID: 5,
PrimaryKey: "CustomerKey"
}];
/**
* Return an array of objects of which each object has a commonly shared key
* and a value derived from the key of an object of a given array. The object
* itself is determined by the given type of it's value.
* @param {array<object>} array - An array of objects
* @param {string} type - The type a value of an object property to accept
* @param {string} [newKey = "fieldName"] - The name of the commonly shared
* key of each object in the returned array. If undefined it defaults
* to "fieldName".
* @returns {array<object>} - An array of objects (see description above)
*/
function keysByType(array, type, newKey = "fieldName") {
return array.flatMap(obj =>
Object.entries(obj).flatMap(pair =>
typeof pair[1] === type ? {
[newKey]: pair[0]
} : []));
}
console.log(keysByType(data, "string"));