Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Console.log Array value in Object

I have the following object.

let obj = {
  'app': ['placementId'],
  'app2': ['siteId'],
  'app3': ['channel_id'],
};

function search(y) {
  return Object.keys(obj).filter((x, id, arr) => {
    console.log(obj['app'][0]) // returns 'placementId'
    if (x == y) {
      return obj[y][0] // returns ['app']
    }
  })
};

let result = search('app');
console.log(result);

I don’t really understand why the function returns [‘app’] and not placementId, like it did in the console.log statement. Thank you!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Filter doesn’t work like you think it does. return obj[y][0] does not return ['app'] as your comment says. .filter does.

Filter takes an array, and will keep or discard every element inside, depending if you return true or false (or at least something "truthy" or "falsy"). Here, you start with ['app', 'app2', 'app3'] and inside the filter, you return obj['app'][0], which is ['placementId']. This something "truthy" (meaning, not false/null/undefined), so 'app' is kept, and the rest is discarded. The starting array was ['app', 'app2', 'app3'] and the filtered array is ['app'].

What you are trying to do can simply be done this way :

let obj = {
  'app': ['placementId'],
  'app2': ['siteId'],
  'app3': ['channel_id'],
};

const search = y => obj[y][0];

let result = search('app');
console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading