Assuming you want to find the substring in the property value, you can use the following code:
const arr = [
{a:'abc', b:'efg', c:'hij'},
{a:'abc', b:'efg', c:'hij'},
{a:'123', b:'456', c:'789'},
];
const search = 'a';
const res = arr.filter(obj => Object.values(obj).some(val => val.includes(search)));
console.log(res);
If you want to search the property name, use Object.keys instead of Object.values.
Please note that Object.values is a feature of ES2017.
Assuming you want to find the substring in the property value, you can use the following code:
const arr = [
{a:'abc', b:'efg', c:'hij'},
{a:'abc', b:'efg', c:'hij'},
{a:'123', b:'456', c:'789'},
];
const search = 'a';
const res = arr.filter(obj => Object.values(obj).some(val => val.includes(search)));
console.log(res);
If you want to search the property name, use Object.keys instead of Object.values.
Please note that Object.values is a feature of ES2017.
Works like a charm:
data.filter((obj) =>
JSON.stringify(obj).toLowerCase().includes(query.toLowerCase())
)
Finding the array element:
let arr = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
let obj = arr.find(o => o.name === 'string 1');
console.log(obj);
Replacing the array element:
let arr = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
let obj = arr.find((o, i) => {
if (o.name === 'string 1') {
arr[i] = { name: 'new string', value: 'this', other: 'that' };
return true; // stop searching
}
});
console.log(arr);
You can loop over the array and test for that property:
function search(nameKey, myArray){
for (let i=0; i < myArray.length; i++) {
if (myArray[i].name === nameKey) {
return myArray[i];
}
}
}
const array = [
{ name:"string 1", value:"this", other: "that" },
{ name:"string 2", value:"this", other: "that" }
];
const resultObject = search("string 1", array);
console.log(resultObject)
Videos
If you look closely you will notice that:
- You do not check if
.matchmatched (it returnsnullon no match; testing fornull.lengthwill throw an error) - You are checking
match.length > 1... the syntax you are using will return an array with exactly one item or null - You are missing the return statement for
.filter - You do not assign the return value of
.filterto any variable
Here is what you need to do:
var filteredItems = items.filter(function (item) {
return defConfigs.some(function (def) {
return (def.key in item)
? item[def.key].toString().toLowerCase().match('low') !== null
: false;
});
});
console.log(filteredItems);
String.prototype.match() function will return null if there are no matches, therefore you need check this case. Next you could use Array.prototype.some() function to verify that at least one item in array is fulfilling your condition. For example:
items.filter(item =>
// check if at least one key from `defConfigs` on `item` matches 'low'
defConfigs.some((def) => {
if (def.key in item) {
const matched = item[def.key].toString().toLowerCase().match('low')
// return true if item matched
return !!matched
}
// match not found by default
return false
}));
Use the find() method:
myArray.find(x => x.id === '45').foo;
From MDN:
The
find()method returns the first value in the array, if an element in the array satisfies the provided testing function. Otherwiseundefinedis returned.
If you want to find its index instead, use findIndex():
myArray.findIndex(x => x.id === '45');
From MDN:
The
findIndex()method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.
If you want to get an array of matching elements, use the filter() method instead:
myArray.filter(x => x.id === '45');
This will return an array of objects. If you want to get an array of foo properties, you can do this with the map() method:
myArray.filter(x => x.id === '45').map(x => x.foo);
Side note: methods like find() or filter(), and arrow functions are not supported by older browsers (like IE), so if you want to support these browsers, you should transpile your code using Babel (with the polyfill).
As you are already using jQuery, you can use the grep function which is intended for searching an array:
var result = $.grep(myArray, function(e){ return e.id == id; });
The result is an array with the items found. If you know that the object is always there and that it only occurs once, you can just use result[0].foo to get the value. Otherwise you should check the length of the resulting array. Example:
if (result.length === 0) {
// no result found
} else if (result.length === 1) {
// property found, access the foo property using result[0].foo
} else {
// multiple items found
}
Thanks for providing some example code. That helps.
Let's start with your function, which has a good signature:
const excludeItems = (arrayOfSearchItems, arrayOfObjects) => { ... }
If we describe what this function should do, we would say "it returns a new array of objects which do not contain any of the search items." This gives us a clue about how we should write our code.
Since we will be returning a filtered array of objects, we can start by using the filter method:
return arrayOfObjects.filter(obj => ...)
For each object, we want to make sure that its storage does not contain any of the search items. Another way to word this is "every item in the starage array does NOT appear in the list of search items". Now let's write that code using the every method:
.filter(obj => {
// ensure "every" storage item matches a condition
return obj.storage.every(storageItem => {
// the "condition" is that it is NOT in the array search items
return arrayOfSearchItems.includes(storageItem) === false);
});
});
Putting it all together:
const excludeItems = (arrayOfSearchItems, arrayOfObjects) => {
return arrayOfObjects.filter(obj => {
return obj.storage.every(storageItem => {
return arrayOfSearchItems.includes(storageItem) === false;
});
});
}
Here's a fiddle: https://jsfiddle.net/3p95xzwe/
You can achieve your goal by using some of the built-in Array prototype functions, like filter, some and includes.
const excludeItems = (search, objs) =>
objs.filter(({storage:o}) => !search.some(s => o.includes(s)));
In other words: Filter my array objs, on the property storage to keep only those that they dont include any of the strings in search.
It's as simple as iterating the array and looking for the regexp
function searchStringInArray (str, strArray) {
for (var j=0; j<strArray.length; j++) {
if (strArray[j].match(str)) return j;
}
return -1;
}
Edit - make str as an argument to function.
You can use Array.prototype.find function in javascript. Array find MDN.
So to find string in array of string, the code becomes very simple. Plus as browser implementation, it will provide good performance.
Ex.
var strs = ['abc', 'def', 'ghi', 'jkl', 'mno'];
var value = 'abc';
strs.find(
function(str) {
return str == value;
}
);
or using lambda expression it will become much shorter
var strs = ['abc', 'def', 'ghi', 'jkl', 'mno'];
var value = 'abc';
strs.find((str) => str === value);