简体   繁体   中英

javascript / es6 - how to get index of first object value whos array length is greater than 0

I have an object which is full of arrays:

const errors = { name: [], date: ['invalid format'], ... }

I want to find the index (or object key, if I can't get an index) of the first value in the errors object where the array length is greater than one. So in the example above, the date array is the first array in the object that has a length, so I would just return, ideally, 1 , or date if necessary.

Anybody know the most concise / fastest way to do this in javascript / es6?

You can use find() on Object.keys() and it will return first result that matches condition or undefined.

 const errors = { name: [], date: ['invalid format']} var result = Object.keys(errors).find(e => errors[e].length); console.log(result) 

JavaScript objects have no inherent order to their properties , so if an index is truly salient you probably want to use an array instead.

At that point it's just something like errors.findIndex(e => e.length > 1) , adjusted as you see fit.

You can use for ..in to loop through the object and Object.prototype.toString to check if the value is an array.

Also to find the index you may need to use Object.keys which will create an array of keys from the object. Js Object does not have index

 const errors = { name: [], test: 1, date: ['invalid format'], test2: 2 } for (var keys in errors) { if (Object.prototype.toString.call(errors[keys]) === '[object Array]' && errors[keys].length > 0) { console.log(errors[keys]) } } 

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