So it's coming from Kraken API and the data does have a guaranteed shape, where as and bs are known keys -
[ Integer // channel
, { as: [ [ Float, Float, Float ] ] // [ price, volume, timestamp ]
, { bs: [ [ Float, Float, Float ] ] // [ price, volume, timestamp ]
]
Suggestions (including my own in the comment above) to loop through your object and dynamically search for the property are the result of XY problem. In this case I would use destructuring assignment -
const messageBook =
[ 0
, { as:
[ [ 5541.30000, 2.50700000, 1534614248.123678 ]
, [ 5541.80000, 0.33000000, 1534614098.345543 ]
, [ 5542.70000, 0.64700000, 1534614244.654432 ]
]
}
, { bs:
[ [ 5541.20000, 1.52900000, 1534614248.765567 ]
, [ 5539.90000, 0.30000000, 1534614241.769870 ]
, [ 5539.50000, 5.00000000, 1534613831.243486 ]
]
}
]
// ! ! !
const doSomething = ([ channel, { as }, { bs } ]) =>
console.log(channel, as, bs)
// 0 [...] [...]
doSomething(messageBook)
In the event you cannot trust the producer, you can use destructuring assignment in combination with default arguments –
const badMessageBook =
[ 0
, { as:
[ [ 5541.30000, 2.50700000, 1534614248.123678 ]
, [ 5541.80000, 0.33000000, 1534614098.345543 ]
, [ 5542.70000, 0.64700000, 1534614244.654432 ]
]
}
// missing { bs: [ ... ] }
]
// ! ! !
const doSomething = ([ channel = 0, { as } = { as: [] }, { bs } = { bs: [] } ]) =>
console.log(channel, as, bs)
// 0 [...] [...]
doSomething(badMessageBook)
In this case, your function gets a little long. You can use multiple lines for added readability -
const doSomething = // helpful whitespace emerges...
( [ channel = 0 // default channel 0
, { as } = { as: [] } // sometimes excluded by Kraken
, { bs } = { bs: [] } // sometimes excluded by Kraken
]
) => console.log(channel, as, bs) // doSomething
{ b: [...] }exist but be in a different position in the array? Could there be an object with multiple array properties? What if there are multiple entries with{ b: [...] }?data.find(x => Object(x) === x && x.hasOwnProperty('b') && Array.isArray(x.b)) !== undefined // => true- that said, I'm sure you're going about this the wrong way. Instead of searching through your data and inspecting data types at runtime, you should choose a well-defined data structure such that you program can know about and rely upon.