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?

2
  • 1
    What do you mean by the index of an object property? Commented Aug 22, 2017 at 17:09
  • 4
    Objects are not ordered, so there is no "first" one and no "index" of the key. There's only the key. Commented Aug 22, 2017 at 17:14

3 Answers 3

1

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)

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

3 Comments

Why not .findIndex() as OP wants the index preferably?
@yuriy636 Because an object does not have a guaranteed order of properties.
Are you sure that it will return first array object ?
0

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.

Comments

0

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

2 Comments

@str any specific reason to not use Object.prototype.toString?
@brk It's ugly, slow, long, hard to remember and can be spoofed in ES6.

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.