1

I'm trying to iterate through an array of unknown properties to find a value that exists within a JSON object although there can exist many objects as well, how can I approach this?

  args1 = ['string', 5, 3, { value: 'value', number: 2, token: 'token' }];
  args2 = [
    'string',
    { token: 'token', name: 'name' },
    1,
    3,
    2,
    { book: 'book' },
  ];

How would i be able to find the property token regardless where it exists like the two examples above?

BitByte
  • 121
  • 6
  • duplicate of https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects?rq=1 ? – Rmaxx Jun 28 '22 at 10:25
  • 1
    ForEach item inside the array, check if it is a JS object. If it is an object, check if it hasOwnProperty token. If the object has a property named token, you found it. – Shilly Jun 28 '22 at 10:25
  • What is the value you want to see returned? "token"? – trincot Jun 28 '22 at 10:32
  • Yes token would be the value to return once found. I'm doing this approach like @Shilly said by mapping the array and doing argProperty instanceof Object && argValue.hasOwnProperty('token") then I would return argValue.token Not sure if this is the most ideal solution? – BitByte Jun 28 '22 at 10:36
  • Although that does seem to give me undefined `argValue instanceof Object && argValue.hasOwnProperty('recaptchaToken') ? argValue.token : " ";` – BitByte Jun 28 '22 at 10:41
  • checkout `_lodash.get` -- its the only function I use from lodash anymore and can be loaded without requiring the entire library. – chovy Jun 28 '22 at 10:48

2 Answers2

0

May be something like this:

let args1 = ['string', 5, 3, { value: 'value', number: 2, token: 'token' }];

args1.filter(x=> typeof x==='object').find(y => console.log(y.token));
Ashish Patil
  • 4,428
  • 1
  • 15
  • 36
0

Object.assign can turn everything to a single object, and then you can deal with it in a single way:

const findProp = (arr, prop) => Object.assign({}, ...arr)[prop];

var args1 = ['string', 5, 3, { value: 'value', number: 2, token: 'token' }];
console.log(findProp(args1, "token"));
trincot
  • 317,000
  • 35
  • 244
  • 286