Merging multiple arrays on shared keys in Javascript - javascript

I want to merge multiple arrays into one big array with shared keys.
What I've tried:
var conditions = [];
if( aa != undefined )
{
conditions.push( { "query" : { "must" : { "aa" : "this is aa" } } } );
}
if( bb != undefined )
{
conditions.push( { "query" : { "must" : { "bb" : "this is bb" } } } );
}
The above code is giving:
[
{
"query": {
"must": {
"aa": "this is aa"
}
}
},
{
"query": {
"must": {
"bb": "this is bb"
}
}
}
]
But I need this:
[
{
"query": {
"must": [
{
"aa": "this is aa"
},
{
"bb": "this is bb"
}
]
}
}
]
I am able to do it with PHP but I need to do it in native javascript or using underscore.js

Define the object your pushing - push everything to the inner array first - then push the object to the outer array:
var conditions = [];
var query = { query: {} };
if( aa != undefined ) {
if (!query["query"]["must"]) {
query["query"]["must"] = [];
}
//conditions.push( { "query" : { "must" : { "aa" : "this is aa" } } } );
query["query"]["must"].push({ "aa" : "this is aa" });
}
if( bb != undefined ) {
if (!query["query"]["must"]) {
query["query"]["must"] = [];
}
//conditions.push( { "query" : { "must" : { "bb" : "this is bb" } } } );
query["query"]["must"].push({ "bb" : "this is bb" });
}
conditions.push(query);

For each descendant of conditions, check if it exists, create it if it doesn't.
Then, finally, push your new object:
function addCondition(conditions, key, value) {
conditions[0] = conditions[0] || {};
conditions[0].query = conditions[0].query || {};
conditions[0].query.must = conditions[0].query.must || [];
var o = {};
o[key] = value;
conditions[0].query.must.push( o );
}
var conditions = [];
var aa = 1, bb = 1;
if (typeof(aa) !== 'undefined')
addCondition(conditions, "aa", "this is aa" );
if (typeof(bb) !== 'undefined')
addCondition(conditions, "bb", "this is bb" );
if (typeof(cc) !== 'undefined')
addCondition(conditions, "cc", "this is cc" );
document.getElementById('results').innerHTML = JSON.stringify(conditions, null, 2);
<pre id="results"></pre>

It's not quite trivial, because I see you want to make an array out of the last inner property.
Do those Objects you push into the conditions array already exist or are you defining them yourself?
You can solve your problem with a recursive function like this I believe:
EDIT: The code produces the exact result you wanted now.
var object1 = {
query: {
must: {
aa: "this is aa"
}
}
}
var object2 = {
query: {
must: {
bb: "this is bb"
}
}
}
var conditions = {};
function mergeObjects(object, parentObject){
for(var prop in object){
if(parentObject.hasOwnProperty(prop)){
if(typeof parentObject[prop] === "object" && shareProperties(parentObject[prop], object[prop])){
mergeObjects(object[prop], parentObject[prop])
}else{
parentObject[prop] = [parentObject[prop], object[prop]];
}
}else{
parentObject[prop] = object[prop];
}
}
}
function shareProperties(obj1, obj2){
for(var prop in obj1){
if(obj2.hasOwnProperty(prop)){
return true;
}
}
return false;
}
mergeObjects(object1, conditions);
mergeObjects(object2, conditions);
Output:
"{"query":{"must":[{"aa":"this is aa"},{"bb":"this is bb"}]}}"

Related

Get path to JSON object by key?

Given the following object:
const ourObject = {
"payload": {
"streams": [
{
"children": {
"2165d20a-6276-468f-a02f-1abd65cad618": {
"additionalInformation": {
"narrative": {
"apple": "A",
"banana": "B"
},
"myInventory": {
"fruits": [
{
"name": "apple"
},
{
"name": "banana"
}
]
}
}
}
}
}
]
}
};
We're trying to find the path of myInventory, the issue is that the children's uuid will be different each time. Any idea how we can get the path to myInventory by providing it as a key and get the json path to it?
If things are dynamic, a programmatic key search could help
const ourObject = {
"payload": {
"streams": [
{
"children": {
"2165d20a-6276-468f-a02f-1abd65cad618": {
"additionalInformation": {
"narrative": {
"apple": "A",
"banana": "B"
},
"myInventory": {
"fruits": [
{
"name": "apple"
},
{
"name": "banana"
}
]
}
}
}
}
}
]
}
};
const getPath = (key, o) => {
if (!o || typeof o !== "object") {
return "";
}
const keys = Object.keys(o);
for(let i = 0; i < keys.length; i++) {
if (keys[i] === key ) {
return key;
}
const path = getPath(key, o[keys[i]]);
if (path) {
return keys[i] + "." + path;
}
}
return "";
};
const getValueForKey = (key, o) => {
if (!o || typeof o !== "object") {
return undefined;
}
const keys = Object.keys(o);
for(let i = 0; i < keys.length; i++) {
if (keys[i] === key ) {
return o[key];
}
const value = getValueForKey(key, o[keys[i]]);
if (value) {
return value;
}
}
return undefined;
}
console.log(getPath("myInventory", ourObject))
console.log(getValueForKey("myInventory", ourObject))
Not sure if I understand the question right but
let uuid = '2165d20a-6276-468f-a02f-1abd65cad618';
ourObject.payload.streams[0].children[uuid].additionalInformation.myInventory
var changingKey = Object.keys(ourObject["payload"]["streams"][0]["children"])[0];
console.log(ourObject["payload"]["streams"][0]["children"][changingKey]["additionalInformation"]["myInventory"]);
Okay, you could create a helper function that gets the UUID. Since it's an object, the lookup is close to O(1) especially given the case that the children has only one key-value pair here.
function getUUIDFromPayload(payload) {
let obj = payload.streams[0].children
let uuid = Object.keys(obj)[0]
return uuid
}
Usage
const uuid = getUUIDFromPayload(payload)
ourObject.payload.streams[0].children[uuid].additionalInformation.myInventory

javascript return property value from nested array of objects based on condition

i have an array of objects, in which each object could have an array of objects inside.
var mylist = [
{
"email" : null,
"school" : "schoolA",
"courses": [
{
"name" : 'ABC',
"type" : "chemistry"
},
{
"name" : 'XYZ',
"type": "math"
}
]
},
{
"email" : null,
"school": "schoolB"
}
];
i want to return course name if one of the course type is chemistry.
The course types are unique and even if they are some duplicates, we return the first one.
var result = mylist.some(function (el) {
el.courses && el.courses.some(function(u) {
if (u.type === 'chemistry') {
return u.name;
};
})
});
console.log('outcome:', result);
my code is not working at this stage.
The some callback should return a truthy or falsy value, which tells some whether to keep going (true = stop), and some returns a boolean, not a callback return value.
Probably simplest in this case just to assign directly to result:
var result;
mylist.some(function(el) {
return (el.courses || []).some(function(course) {
if (course.type === "chemistry") {
result = course.name;
return true;
}
return false;
});
});
Live Example:
var mylist = [
{
"email" : null,
"school" : "schoolA",
"courses": [
{
"name" : 'ABC',
"type" : "chemistry"
},
{
"name" : 'XYZ',
"type": "math"
}
]
},
{
"email" : null,
"school": "schoolB"
}
];
var result;
mylist.some(function(el) {
return (el.courses || []).some(function(course) {
if (course.type === "chemistry") {
result = course.name;
return true;
}
return false;
});
});
console.log(result);
I stuck to ES5 syntax since you didn't use any ES2015+ in your question, but in ES2015+, simplest probably to use nested for-of loops:
let result;
outer: for (const el of mylist) {
for (const course of el.courses || []) {
if (course.type === "chemistry") {
result = course.name;
break outer;
}
}
}
Live Example:
const mylist = [
{
"email" : null,
"school" : "schoolA",
"courses": [
{
"name" : 'ABC',
"type" : "chemistry"
},
{
"name" : 'XYZ',
"type": "math"
}
]
},
{
"email" : null,
"school": "schoolB"
}
];
let result;
outer: for (const el of mylist) {
for (const course of el.courses || []) {
if (course.type === "chemistry") {
result = course.name;
break outer;
}
}
}
console.log(result);
You could use reduce() method to iterate through each object in array and then find() method to find if some course matches type.
var mylist = [{"email":null,"school":"schoolA","courses":[{"name":"ABC","type":"chemistry"},{"name":"XYZ","type":"math"}]},{"email":null,"school":"schoolB"}]
const course = mylist.reduce((r, {courses}) => {
if (courses && !r) {
const course = courses.find(({type}) => type == 'chemistry');
if (course) r = course.name;
}
return r;
}, null)
console.log(course)

How to convert following Json object as a string like below

I have a json object as follows,
{
"category": "music",
"location": {
"city": "Braga"
},
"date": {
"start": {
"$gte": "2017-05-01T18:30:00.000Z"
},
"end": {
"$lt": "2017-05-12T18:30:00.000Z"
}
}
}
i need to create a query string as follows,
category=music | location.city = Braga | date.start.$gte = 2017-05-01T18:30:00.000Z | date.end.$lt = 2017-05-12T18:30:00.000Z
How can I achieve this?
This is what i have tried.
_.each(this.filter, (val: string, key: string) => {
if (key && val) {
filterArray.push(`${key}=${val}`);
}
});
You could iterate the keys and build a path to the value. Later join pathes and add value and join to the final string.
function getParts(object) {
function iter(o, p) {
Object.keys(o).forEach(function (k) {
if (o[k] && typeof o[k] === 'object') {
iter(o[k], p.concat(k));
return;
}
result.push(p.concat(k).join('.') + ' = ' + o[k]);
});
}
var result = [];
iter(object, []);
return result.join(' | ');
}
var object = { "category": "music", "location": { "city": "Braga" }, "date": { "start": { "$gte": "2017-05-01T18:30:00.000Z" }, "end": { "$lt": "2017-05-12T18:30:00.000Z" } } },
string = getParts(object);
console.log(string);
Sorry, I'm late, but still.
Method walk recursively runs through your JSON and calls callback function with chain of keys and value as arguments.
Then convert uses walk to translate JSON into your format:
var walk = function( data, iterator, stack ) {
var key;
stack = stack || [];
for ( key in data ) {
if ( typeof data[ key ] === 'string' ) {
iterator( stack.concat( [ key ] ), data[ key ] );
} else {
walk( data[ key ], iterator, stack.concat( [ key ] ) );
}
}
};
var convert = function( data ) {
var result = [];
walk( data, function( keys, value ) {
result.push( keys.join( '.' ) + ' = ' + value );
} );
return result.join( ' | ' );
};
var query_string = convert( /* your JSON here */ );

transformation- in to an array

Input:
{ key : "value" ,
list : [
{
key : "values1" ,
list : [
{ key : "value2" , list :[{ key : "simpleValue" } ]
}
]
},
{
key : "value3"
}
]
}
Output:
{key : ["value" , "values1" , "values2" , "simpleeValue", "values3"]}
the code that I wrote for conversion is
var outputArray=new Array();
var count=0;
function recursion(testData){
if(testData.key==undefined)
{
return ;
}
else
{
outputArray[count]=testData.key;
count++;
for(var k in testData.list)
{
testData1=testData.list[k];
recursion(testData1);
recursion(testData.key);
}
}
return outputArray;
}
The output will only give me the value list an array,like [
'value',
'values1',
'value2',
'simpleValue',
'value3'
], how do I use the hash method to get the correct output?
Hmm, something like this??
var inpObj = { key : "value" ,list : [
{
key : "values1"
},
{
key : "value3"
}
]
};
var outputObj = new Object;
var outputArray = new Array();
function recursion(testData){
if(testData.key==undefined)
{
return;
}
else
{
var newKey={};
//alert(testData.key);
outputArray.push(testData.key);
for(var k in testData.list)
{
testData1=testData.list[k];
recursion(testData1);
recursion(testData.key);
}
}
return outputArray;
}
recursion(inpObj);
if (outputObj.key == undefined) outputObj.key = outputArray;
alert(outputObj.key.join(", "));
I got this thing sorted out
var outputArray=new Array();
function recursion(testData){
if(testData.key==undefined)
{
return ;
}
else
{
//alert(testData.key);
outputArray.push(testData.key);
for(var k in testData.list)
{
testData1=testData.list[k];
recursion(testData1);
recursion(testData.key);
}
}
var l={};
l.key=outputArray;
return l;
}

JS search in object values

I have an array of homogeneous objects like so;
[
{
"foo" : "bar",
"bar" : "sit"
},
{
"foo" : "lorem",
"bar" : "ipsum"
},
{
"foo" : "dolor",
"bar" : "amet"
}
]
I'd like to search these objects' values (not keys) with a keyword, and return an array of objects that contain the keyword in any of the values.
So for example, with a keyword r, I would get all the objects ("baR" in object #1, "loRem" in object #2 and "doloR" in object #3). With a keyword lo, I would get objects 2 and 3 ("LOrem" and "doLOr"), with a, I'd get objects 1 and 3, ("bAr" and "Amet"). With the keyword foo however, I would get an empty array, since "foo" is a key, and isn't found in any of the values (unlike "bar")... you get the idea.
How would I go about doing this? Thanks a lot in advance!
Something like this:
var objects = [
{
"foo" : "bar",
"bar" : "sit"
},
{
"foo" : "lorem",
"bar" : "ipsum"
},
{
"foo" : "dolor",
"bar" : "amet"
}
];
var results = [];
var toSearch = "lo";
for(var i=0; i<objects.length; i++) {
for(key in objects[i]) {
if(objects[i][key].indexOf(toSearch)!=-1) {
results.push(objects[i]);
}
}
}
The results array will contain all matched objects.
If you search for 'lo', the result will be like:
[{ foo="lorem", bar="ipsum"}, { foo="dolor", bar="amet"}]
NEW VERSION - Added trim code, code to ensure no duplicates in result set.
function trimString(s) {
var l=0, r=s.length -1;
while(l < s.length && s[l] == ' ') l++;
while(r > l && s[r] == ' ') r-=1;
return s.substring(l, r+1);
}
function compareObjects(o1, o2) {
var k = '';
for(k in o1) if(o1[k] != o2[k]) return false;
for(k in o2) if(o1[k] != o2[k]) return false;
return true;
}
function itemExists(haystack, needle) {
for(var i=0; i<haystack.length; i++) if(compareObjects(haystack[i], needle)) return true;
return false;
}
var objects = [
{
"foo" : "bar",
"bar" : "sit"
},
{
"foo" : "lorem",
"bar" : "ipsum"
},
{
"foo" : "dolor blor",
"bar" : "amet blo"
}
];
function searchFor(toSearch) {
var results = [];
toSearch = trimString(toSearch); // trim it
for(var i=0; i<objects.length; i++) {
for(var key in objects[i]) {
if(objects[i][key].indexOf(toSearch)!=-1) {
if(!itemExists(results, objects[i])) results.push(objects[i]);
}
}
}
return results;
}
console.log(searchFor('lo '));
All the other old answers use a for in loop, modern JavaScript has Object.keys. Combine that with some, includes, and filter and it is a bit nicer.
var a = [{
name: 'xyz',
grade: 'x'
}, {
name: 'yaya',
grade: 'x'
}, {
name: 'x',
frade: 'd'
}, {
name: 'a',
grade: 'b'
}];
function filterIt(arr, searchKey) {
return arr.filter(function(obj) {
return Object.keys(obj).some(function(key) {
return obj[key].includes(searchKey);
})
});
}
console.log("find 'x'", filterIt(a,"x"));
console.log("find 'a'", filterIt(a,"a"));
console.log("find 'z'", filterIt(a,"z"));
Or with ES6
function filterIt(arr, searchKey) {
return arr.filter(obj => Object.keys(obj).some(key => obj[key].includes(searchKey)));
}
This is a cool solution that works perfectly
const array = [{"title":"tile hgfgfgfh"},{"title":"Wise cool"},{"title":"titlr DEytfd ftgftgfgtgtf gtftftft"},{"title":"This is the title"},{"title":"yeah this is cool"},{"title":"tile hfyf"},{"title":"tile ehey"}];
var item = array.filter(item=>item.title.toLowerCase().includes('this'));
alert(JSON.stringify(item))
EDITED
const array = [{"title":"tile hgfgfgfh"},{"title":"Wise cool"},{"title":"titlr DEytfd ftgftgfgtgtf gtftftft"},{"title":"This is the title"},{"title":"yeah this is cool"},{"title":"tile hfyf"},{"title":"tile ehey"}];
// array.filter loops through your array and create a new array returned as Boolean value given out "true" from eachIndex(item) function
var item = array.filter((item)=>eachIndex(item));
//var item = array.filter();
function eachIndex(e){
console.log("Looping each index element ", e)
return e.title.toLowerCase().includes("this".toLowerCase())
}
console.log("New created array that returns \"true\" value by eachIndex ", item)
This is a proposal which uses the key if given, or all properties of the object for searching a value.
function filter(array, value, key) {
return array.filter(key
? a => a[key] === value
: a => Object.keys(a).some(k => a[k] === value)
);
}
var a = [{ name: 'xyz', grade: 'x' }, { name: 'yaya', grade: 'x' }, { name: 'x', frade: 'd' }, { name: 'a', grade: 'b' }];
console.log(filter(a, 'x'));
console.log(filter(a, 'x', 'name'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
This is a succinct way with modern Javascript:
var objects = [
{
"foo" : "bar",
"bar" : "sit"
},
{
"foo" : "lorem",
"bar" : "ipsum"
},
{
"foo" : "dolor blor",
"bar" : "amet blo"
}
];
const query = "lo";
const filteredItems = objects.filter(item => `${item.foo} ${item.bar}`.includes(query));
The search function will return all objects which contain a value which has contains the search query
function search(arr, s){
var matches = [], i, key;
for( i = arr.length; i--; )
for( key in arr[i] )
if( arr[i].hasOwnProperty(key) && arr[i][key].indexOf(s) > -1 )
matches.push( arr[i] ); // <-- This can be changed to anything
return matches;
};
// dummy data
var items = [
{
"foo" : "bar",
"bar" : "sit"
},
{
"foo" : "lorem",
"bar" : "ipsum"
},
{
"foo" : "dolor",
"bar" : "amet"
}
];
var result = search(items, 'lo'); // search "items" for a query value
console.log(result); // print the result
Modern Javascript 😄
const objects = [
{
"foo" : "bar",
"bar" : "sit"
},
{
"foo" : "lorem",
"bar" : "ipsum"
},
{
"foo" : "dolor blor",
"bar" : "amet blo"
}
];
const keyword = 'o';
const results = objects.filter(object => Object.values(object).some(i => i.includes(keyword)));
console.log(results);
// results [{ foo: 'lorem', bar: 'ipsum' },{ foo: 'dolor blor', bar: 'amet blo' }]
var search(subject, objects) {
var matches = [];
var regexp = new RegExp(subject, 'g');
for (var i = 0; i < objects.length; i++) {
for (key in objects[i]) {
if (objects[i][key].match(regexp)) matches.push(objects[i][key]);
}
}
return matches;
};
var items = [
{
"foo" : "bar",
"bar" : "sit"
},
{
"foo" : "lorem",
"bar" : "ipsum"
},
{
"foo" : "dolor",
"bar" : "amet"
}
];
search('r', items); // ["bar", "lorem", "dolor"]
As a Javascripter Lv. 1 I just learned to search for strings in objects with this:
function isThere( a_string, in_this_object )
{
if( typeof a_string != 'string' )
{
return false;
}
for( var key in in_this_object )
{
if( typeof in_this_object[key] == 'object' || typeof in_this_object[key] == 'array' )
{
if ( isThere( a_string, in_this_object[key] ) )
{
return true;
}
}
else if( typeof in_this_object[key] == 'string' )
{
if( a_string == in_this_object[key] )
{
return true;
}
}
}
return false;
}
I know is far from perfect but it is useful.
Feel free to comment in order to improve this.
search(searchText) {
let arrayOfMatchedObjects = arrayOfAllObjects.filter(object => {
return JSON.stringify(object)
.toString()
.toLowerCase()
.includes(searchText);
});
return arrayOfMatchedObjects;
}
This could be very simple, easy, fast and understandable Search function for some of you just like me.
Although a bit late, but a more compact version may be the following:
/**
* #param {string} quickCriteria Any string value to search for in the object properties.
* #param {any[]} objectArray The array of objects as the search domain
* #return {any[]} the search result
*/
onQuickSearchChangeHandler(quickCriteria, objectArray){
let quickResult = objectArray.filter(obj => Object.values(obj).some(val => val?val.toString().toLowerCase().includes(quickCriteria):false));
return quickResult;
}
It can handle falsy values like false, undefined, null and all the data types that define .toString() method like number, boolean etc.
You can use this javascript lib, DefiantJS (http://defiantjs.com), with which you can filter matches using XPath on JSON structures. To put it in JS code:
var data = [
{ "foo": "bar", "bar": "sit" },
{ "foo": "lorem", "bar": "ipsum" },
{ "foo": "dolor", "bar": "amet" }
],
res1 = JSON.search( data, '//*[contains(name(), 'r')]/..' ),
res2 = JSON.search( data, '//*[contains(., 'lo')]' );
/*
res1 = [
{ "foo": "bar", "bar": "sit" },
{ "foo": "lorem", "bar": "ipsum" },
{ "foo": "dolor", "bar": "amet" }
]
*/
/*
res2 = [
{ "foo": "lorem", "bar": "ipsum" },
{ "foo": "dolor", "bar": "amet" }
]
*/
Here is a working fiddle;
http://jsfiddle.net/hbi99/2kHDZ/
DefiantJS extends the global object with the method "search" and returns an array with matches (empty array if no matches were found). You can try out the lib and XPath queries using the XPath Evaluator here:
http://www.defiantjs.com/#xpath_evaluator
I needed to perform a search on a large object and return the addresses of the matches, not just the matched values themselves.
This function searches an object for a string (or alternatively, uses a callback function to perform custom logic) and keeps track of where the value was found within the object. It also avoids circular references.
//Search function
var locateInObject = function(obj, key, find, result, currentLocation){
if(obj === null) return;
result = result||{done:[],found:{}};
if(typeof obj == 'object'){
result.done.push(obj);
}
currentLocation = currentLocation||key;
var keys = Object.keys(obj);
for(var k=0; k<keys.length; ++k){
var done = false;
for(var d=0; d<result.done.length; ++d){
if(result.done[d] === obj[keys[k]]){
done = true;
break;
}
}
if(!done){
var location = currentLocation+'.'+keys[k];
if(typeof obj[keys[k]] == 'object'){
locateInObject(obj[keys[k]], keys[k], find, result, location)
}else if((typeof find == 'string' && obj[keys[k]].toString().indexOf(find) > -1) || (typeof find == 'function' && find(obj[keys[k]], keys[k]))){
result.found[location] = obj[keys[k]];
}
}
}
return result.found;
}
//Test data
var test = {
key1: {
keyA: 123,
keyB: "string"
},
key2: {
keyC: [
{
keyI: "string123",
keyII: 2.3
},
"string"
],
keyD: null
},
key3: [
1,
2,
123,
"testString"
],
key4: "123string"
}
//Add a circular reference
test.key5 = test;
//Tests
console.log(locateInObject(test, 'test', 'string'))
console.log(locateInObject(test, 'test', '123'))
console.log(locateInObject(test, 'test', function(val, key){ return key.match(/key\d/) && val.indexOf('string') > -1}))
Came across this problem today and using a modified version of the provided code by epascarello in this thread did the trick, because that version had trouble when the object contained some values others than strings (like a number of booleans for example).
console.log('find: ', findIn(arrayOfObjects, searchKey));
const findIn = (arr, searchKey) => {
return arr.filter(obj =>
Object.keys(obj).some(key => {
if (typeof obj[key] === 'string') {
return obj[key].includes(searchKey);
}
})
);
};
Here is the answer in 100% PURE JavaScript:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
<script type="text/javascript">
var mySet = [{
"foo": "bar",
"bar": "sit"
},
{
"foo": "lorem",
"bar": "ipsum"
},
{
"foo": "dolor",
"bar": "amet"
}
];
function queryObject(needle, set) {
var results = new Array();
for (index = 0; index < set.length; index++) {
for (key in set[index]) {
if (set[index][key].indexOf(needle) > -1) {
results.push(set[index]);
}
}
}
if (results.length) {
return JSON.stringify(results);
} else {
return "No match!";
}
}
</script>
</head>
<body>
<form>
<input type="text" id="prompt" onFocus="this.value='';" value="Type your query HERE" size="20" onKeyDown="document.getElementById('submit').disabled = false;">
<input id="submit" type="button" value="Find in Object" onClick="var prompt=document.getElementById('prompt'); if(prompt.value){document.getElementById('output').innerHTML = queryObject(prompt.value, mySet);}else{prompt.value='Type your query HERE';}"
disabled="disabled">
<div id="output"></div>
</form>
</body>
</html>
There are, of course, more fancy ways to traverse your object using JQuery, but this is the basic concept.
Cheers!
*EDIT: Sorry, I didn't read your question carefully enough, and modified the code to return an array of objects as you requested.
MAKE SIMPLE
const objects = [
{
"foo" : "bar",
"bar" : "sit",
"date":"2020-12-20"
},
{
"foo" : "lorem",
"bar" : "ipsum",
"date":"2018-07-02"
},
{
"foo" : "dolor",
"bar" : "amet",
"date":"2003-10-08"
},
{
"foo" : "lolor",
"bar" : "amet",
"date":"2003-10-08"
}
];
const filter = objects.filter(item => {
const obj = Object.values(item)
return obj.join("").indexOf('2003') !== -1
})
console.log(filter)
Just another variation using ES6, this is what I use.
// searched keywords
const searchedWord = "My searched exp";
// array of objects
let posts = [
{
text_field: "lorem ipsum doleri imet",
_id: "89789UFJHDKJEH98JDKFD98"
},
{
text_field: "ipsum doleri imet",
_id: "JH738H3JKJKHJK93IOHLKL"
}
];
// search results will be pushed here
let matches = [];
// regular exp for searching
let regexp = new RegExp(searchedWord, 'g');
// looping through posts to find the word
posts.forEach((post) => {
if (post["text_field"].match(regexp)) matches.push(post);
});
Below shared for specific given property
searchContent:function(s, arr,propertyName){
var matches = [];
var propertyNameString=this.propertyNameToStr(propertyName);
for (var i = arr.length; i--; ){
if((""+Object.getOwnPropertyDescriptor(arr[i], propertyNameString).value).indexOf(s) > -1)
matches.push(arr[i]);
}
return matches;
},
propertyNameToStr: function (propertyFunction) {
return /\.([^\.;]+);?\s*\}$/.exec(propertyFunction.toString())[1];
}
//usage as below
result=$localStorage.searchContent(cabNo,appDataObj.getAll(),function() { dummy.cabDriverName; })
I've found a way that you can search in nested object like everything search , for example list of student that have nested lesson object:
var students=[{name:"ali",family:"romandeh",age:18,curse:[
{lesson1:"arabic"},
{lesson2:"english"},
{lesson3:"history"}
]},
{name:"hadi",family:"porkar",age:48,curse:[
{lesson1:"arabic"},
{lesson2:"english"},
{lesson3:"history"}
]},
{name:"majid",family:"porkar",age:30,curse:[
{lesson1:"arabic"},
{lesson2:"english"},
{lesson3:"history"}
]}
];
function searchInChild(objects, toSearch){
var _finded=false;
for(var i=0; i<objects.length; i++) {
for(key in objects[i]) {
if(objects[i][key]!=null && typeof(objects[i][key] )!="boolean" && typeof(objects[i][key] )!="number"){
if (typeof objects[i][key] == 'object') {
_finded= searchInChild(objects[i][key],toSearch);
}
else if(objects[i][key].indexOf(toSearch)!=-1) {
_finded=true;
}
}
}
}
return _finded;
}
function findNested(objects, toSearch) {
var _results=[];
for(var i=0; i<objects.length; i++) {
for(key in objects[i]) {
if(objects[i][key]!=null && typeof(objects[i][key] )!="boolean" && typeof(objects[i][key] )!="number"){
if (typeof objects[i][key] == 'object') {
if(searchInChild(objects[i][key],toSearch)){
_results.push(objects[i]);
}
}
else if(objects[i][key].indexOf(toSearch)!=-1) {
_results.push(objects[i]);
}
}
}
}
return _results;
}
$('.quickSearch').on('click',function(){
var _inputSeach=$('#evertingSearch').val();
if(_inputSeach!=''){
var _finded=findNested(students,_inputSeach);
$('.count').html(_finded.length);}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<span>
<pre><code>
var students=[{name:"ali",family:"romandeh",age:18,curse:[
{lesson1:"arabic"},
{lesson2:"english"},
{lesson3:"history"}
]},
{name:"hadi",family:"porkar",age:48,curse:[
{lesson1:"arabic"},
{lesson2:"english"},
{lesson3:"history"}
]},
{name:"majid",family:"rezaeiye",age:30,curse:[
{lesson1:"arabic"},
{lesson2:"english"},
{lesson3:"history"}
]}
];
</code></pre>
<span>
<input id="evertingSearch" placeholder="Search on students" />
<input type="button" class="quickSearch" value="search" />
<lable>count:</lable><span class="count"></span>
</body>
</html>
I have created this easy to use library that does exactly what you are looking for: ss-search
import { search } from "ss-search"
const data = [
{
"foo" : "bar",
"bar" : "sit"
},
{
"foo" : "lorem",
"bar" : "ipsum"
},
{
"foo" : "dolor",
"bar" : "amet"
}
]
const searchKeys = ["foor", "bar"]
const searchText = "dolor"
const results = search(data, keys, searchText)
// results: [{ "foo": "dolor", "bar": "amet" }]
You can use the _filter method of lodash:
return _filter((item) => item.name.includes("fo"),tempObjectHolder);
you can use modern js with spesific key
const filter = (array, value, key) => {
return array.filter(
key
? (a) => a[key].toLowerCase().includes(value.toLowerCase())
: (a) =>
Object.keys(a).some((k) =>
a[k].toLowerCase().includes(value.toLowerCase())
)
)
}
const data = [
{
"foo" : "bar",
"bar" : "sit"
},
{
"foo" : "lorem",
"bar" : "ipsum"
},
{
"foo" : "dolor blor",
"bar" : "amet blo"
}
];
filter(data, 'o', 'foo')
// results [{ foo: 'lorem', bar: 'ipsum' },{ foo: 'dolor blor', bar: 'amet blo' }]

Categories