简体   繁体   中英

Get values from dynamic object array

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM