0

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

1

3 Answers 3

1

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)
})

Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

1

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())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.