Miha Šušteršič Miha Šušteršič - 26 days ago 5
Javascript Question

javascript - unused argument 'idtype' although called from a .map() function

I am trying to re-write a function that filters out a specific property of an object to a function that can be passed a property and filter it.

This is the initial function:

function filterCategory(xmlObject, id) {
let newData = [];
xmlObject
.Sports[0]
.Sport[0]
.Category
.map(function (category) {
if (category.$.CategoryID == id) {
newData.push(category);
}
});
xmlObject
.Sports[0]
.Sport[0]
.Category = newData;
return xmlObject;
}


This is my new function:

function filterProperty(xmlObject, property, idtype, id) {
let newData = [];

if(xmlObject.hasOwnProperty(property)) {
xmlObject.property.map(function(value) {
if(value.$.idtype == id) {
newData.push(value);
}
});
xmlObject.property = newData;
}
return xmlObject;
}


For the second function my linter returns Unused
idtype
. Will my function be able to access the argument, or will it fail because I am trying to call it from a
map()
function? If so, how can I avoid this?

Answer

If you want to use idtype as a dynamic object property, then you can't use it like my.object.idtype as that will look for the property on the object that is literally called "idtype", instead you can use bracket notation to access the property

value.$[idtype];

Further illustration:

var obj = { one: 1, two: 2, three: 'foobarbaz' };

function getThingFromObject(mything) {  
  return obj[mything];
}

console.log(getThingFromObject('one')); // 1
console.log(getThingFromObject('three')); // 'foobarbaz'