I have an array of objects, with one element being comma separated list of values.
When a new object is created, I want to check if there is an object in the array that, among other things, might contain one or more this comma separated values.
// Test array
var mappings= [
{ "id": 1, "ip": "1.2.3.4", "pain_in_the": "1, 2, 3" },
{ "id": 2, "ip": "5.6.7.8", "pain_in_the": "4, 6, 8" },
{ "id": 3, "ip": "3.4.5.6", "pain_in_the": "5, 7, 9" }
];
var id = $('#tbID').val(); // Lets' say 4
var ip = $('#tbIP').val(); // Let's say "6.7.8.9"
var pit = $('#tbPIT').val(); // This can be "10, 11, 2", with "2" already in first object
When I check, I need to have the first object returned since its pain_in_the field contains "2".
Not sure what to put in ???? placeholder, assuming I am using the right APIs:
// Check
var result = mappings.find(item => item.id=== id || item.ip=== ip || ????? );
var resultAarray = $.grep(mappings, function (item, i) {
return (item.id== id || item.ip== ip || ????);
});
Also, if value of "pit" variable is "10, 2, 8"; with 2 and 8 being in two separate objects in the array, would both objects be returned?
Thank you.
2
Answers
Convert the comma-separated list to an array using
.split()
, then useincludes()
to test if the value is in the array.You can regex any entries delimited with
,
:Add a bit more items and it becomes faster than splitting the string into an array for each item: