I am using a JavaScript library that has some code that expects a simple flat array of items like this...
var items = [
'item 1',
'item 2',
'item 3',
];
This is too limited for my project needs so I am editing the library to accept an array of object instead like this...
var items = [
{
id: 1,
name: 'Item 1',
image: 'img 1',
},
{
id: 2,
name: 'Item 2',
image: 'img 2',
},
{
id: 3,
name: 'Item 3',
image: 'img 3',
},
];
The library calls some code like this...
if (_helpers.inArray(val, this.options.items) || (val === '')) {
return val;
}
It check to see if a string is in the items
array.
Because my items
array is no longer a simple string value and is instead an object now. This breaks this part of the library code.
The code for the function it calls is this...
var _helpers = {
inArray: function(val, arr) {
return ($.inArray(val, arr) !== -1);
},
};
So I need some help in making my own _helpers.inArray(val, this.options.items)
function which will check for a string value in an array of objects under the object property name
Any help appreciated
Could be something like this?
var _helpers = {
inArray: function(val, arr) {
for (var i = 0; i < arr.length; i++){
if (arr[i].name === val)
return true;
}
return false;
},
};
Try mapping your array of objects back to the simple format:
var _helpers = {
inArray: function(val, arr) {
var mappedArr = $.map( items, function(item, index) {
return item.name;
});
return ($.inArray(val, mappedArr) !== -1);
},
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.