简体   繁体   English

JavaScript / ES6-如何获取第一个对象值的索引whos数组长度大于0

[英]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. 我想在数组长度大于1的错误对象中找到第一个值的索引(或对象键,如果无法获取索引)。 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. 因此,在上面的示例中, date数组是对象中具有长度的第一个数组,因此理想情况下,我只会返回1 ,或者在需要时返回date

Anybody know the most concise / fastest way to do this in javascript / es6? 有人知道在javascript / es6中最简洁/最快的方法吗?

You can use find() on Object.keys() and it will return first result that matches condition or undefined. 您可以在Object.keys() find()上使用find() ,它将返回匹配条件或未定义的第一个结果。

 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. JavaScript对象的属性没有固有的顺序 ,因此,如果索引确实是显着的,则可能要使用数组。

At that point it's just something like errors.findIndex(e => e.length > 1) , adjusted as you see fit. 那时,它就像errors.findIndex(e => e.length > 1) ,可以根据需要进行调整。

You can use for ..in to loop through the object and Object.prototype.toString to check if the value is an array. 您可以使用for ..in通过对象和循环Object.prototype.toString检查,如果值是一个数组。

Also to find the index you may need to use Object.keys which will create an array of keys from the object. 另外,要查找索引,您可能需要使用Object.keys,它将从对象创建一个键数组。 Js Object does not have index Js对象没有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]) } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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