Hello In Javascript I get error result from API result array object can be
{
ProjectName:["Invalid Project Name"],
entityName:["Invalid entityName"]
}
or
{
ProjectName:["Invalid Project Name"],
}
and key names are dynamic which comes from API. so I just need values as
["Invalid Project Name","Invalid entityName"]
How can I convert this object to this array ?
Thanks in advance
CodePudding user response:
var errors = [];
var obj = {
ProjectName: ["Invalid Project Name"],
entityName: ["Invalid entityName"],
};
Object.keys(obj).map((k) => {
obj[k].map((x) =>
errors.push({
key: k,
message: x,
})
);
});
errors.map(k => {
console.log("Check " k.key " field: " k.message)
})
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You can use Object.keys
method with reduce
const obj = {
ProjectName:["Invalid Project Name"],
entityName:["Invalid entityName"]
}
const result = Object.keys(obj).reduce((prev, curr) => {
prev.push(obj[curr][0]);
return prev;
}, []);
console.log(result);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You can use Object.values
combined with map and flat:
var obj = {
ProjectName: ["Invalid Project Name"],
entityName: ["Invalid entityName"],
};
console.log(Object.values(obj).map(i => i).flat())
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>