1

So I have a structure like that:

Foo: {
    A: Array[0],
    B: Array[0],
    C: Array[1]
}

where [X] is length of the array, but Foo is an object, not an Array, therefore I can't use Array method on it.

How do I get first element (letter in this case) which has length > 0 ?

for (let letter in Foo) {
    if (letter.length > 0) {
        let match = letter;
    }
}

I tried something like this (this is simplified version), but it just returns all properties of Foo.

knitevision
  • 3,023
  • 6
  • 29
  • 44
  • 5
    There is no concept of "first" in an object, the properties are not ordered. Also, *let* is block scoped so you will have difficultly returning *match* from outside the block. – RobG Jun 01 '16 at 00:55
  • @RobG condition is supposed to return a set of Arrays which match the criteria. I just want to pick the 1st one out of this set. It's not realistic? – knitevision Jun 01 '16 at 00:57
  • You can do that, but the value returned may be different in different hosts so the result is not reliable. – RobG Jun 01 '16 at 00:59
  • Related to @RobG's comment: http://stackoverflow.com/a/5525820/4475267 – noisypixy Jun 01 '16 at 01:03
  • @knitevision: If you want to pick *any* of that set it's ok - but don't expect to get the same result every time you run this. As Rob said, there is no "1st one" in an unordered set. – Bergi Jun 01 '16 at 01:03

1 Answers1

1

I’m glad you’re using ES6. In this case you can use Object.keys to get an array of all the object’s keys and Array.prototype.find to find the first element with a specific property:

var obj = {
  a: [],
  b: [],
  c: [
    2,
    3
  ],
  d: [],
  e: [
    1
  ]
};

Object.keys(obj).find(a => obj[a].length > 0); // The letter "c" which contains the first non-empty array.

obj[Object.keys(obj).find(a => obj[a].length > 0)]; // Array [2, 3] itself

Note that there’s no consistent “first” element in an object across implementations.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75