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!
>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);