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!
CodePudding user response:
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);
CodePudding user response:
You should have returned obj[x]
or obj[y]
, as when you pass the Obj[key]
it gives out value. You are trying to give wrong output.
let obj={
'app': ['placementId'],
'app2': ['siteId'],
'app3': ['channel_id'],
};
function search(y){
return Object.keys(obj).filter((x, id, arr)=> {
if(x===y) {
console.log(x,y); //gives out 'app app'
console.log(obj[x]); //gives out [placementId]
console.log(obj[x][0]); //gives out placementId
return obj[y]
}
})
};
console.log(search('app')); //filter will only give that item (out of multiple), where conditions matched, so output is 'app' (in the item out of all, where condition matched);
CodePudding user response:
Because filter callback return boolean value to filter array. If you want find first by key it should be like that:
let obj={
'app': ['placementId'],
'app2': ['siteId'],
'app3': ['channel_id'],
};
function search(y){
return obj[Object.keys(obj).find((x)=> x === y)][0];
};
search('app');
No need to use filter function in this current case:
function search(y){
return obj[y][0]
};