Comparing two nested JSON structures - javascript

I'm trying to compare two JSON structures by their keys, not the values inside the keys.
The goal is to see if the one is different by the other. I don't need a diff, just a simple flag. I've tried to do it but somehow I can't get a solution that would not be overcomplicated.
Sample JSON1 structure
{ "parentKey" :
{ "childKey" : { "nestedKey" : "value" },
"childKey2: "value2" }}
JSON2
{ "parentKey" :
{ "childKey" : { "nestedKey" : "value2",
"nestedKey2": "value3"},
"childKey2: "value2" }}

If you only need to see if the 2 objects are not exactly identical (just the keys, not the values) It's pretty simple, you just check Every key in both objects. If you need to know what key is different or how is different it's entirely a different problem.
let o1 = { "parentKey" :
{ "childKey" : { "nestedKey" : "value" },
"childKey2": "value2" }}
let o2 = { "parentKey" :
{ "childKey" : { "nestedKey" : "value2",
"nestedKey2": "value3"},
"childKey2": "value2" }}
let keysInObj1 = []
let keysInObj2 = []
function compare(object, arr){
for (const obj in object){
arr.push(obj)
if(typeof(object[obj]) == 'object'){
compare(object[obj], arr)
}
}
}
compare(o1, keysInObj1)
compare(o2, keysInObj2)
keysInObj1.forEach((val, index)=>{
if(keysInObj2[index] != val){
console.log('Objects are not the same')
}
})
JsFiddle

Here is an iterative solution using object-scan
This solution could easily be modified to tell you exactly the keys that the objects are different.
// const objectScan = require('object-scan');
const d1 = { parentKey: { childKey: { nestedKey: 'value' }, childKey2: 'value2' } };
const d2 = { parentKey: { childKey: { nestedKey: 'value2', nestedKey2: 'value3' }, childKey2: 'value2' } };
const cmp = (a, b) => {
const r1 = objectScan(['**'], { joined: true })(a);
const r2 = objectScan(['**'], { joined: true })(b);
if (r1.length !== r2.length) {
return false;
}
return r1.every((e) => r2.includes(e));
};
console.log(cmp(d1, d2));
// => false
console.log(cmp(d1, d1));
// => true
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#14.3.1"></script>
Disclaimer: I'm the author of object-scan

const compareKeys = (obj1, obj2) =>
Object.keys(obj1).length === Object.keys(obj2).length &&
Object.keys(obj1).every((key) => key in obj2);
var object1 = {
"banana": "bar",
"orange": "foo"
};
var object2 = {
"banana": "foo",
"orange": "bar"
};
var object3 = {
"aaaaa": "bar",
"jjjjj": "foo"
};
//Expected output: true
console.log(compareKeys(object1, object2));
//Expected output: false
console.log(compareKeys(object1, object3));

I have tried this approach keep in mind the structure should be same too.
Therefore,
{name: "Anuj", isTaxPayer: true}
{isTaxPayer: true, name: "Shonster"}
will not be same
var keys1 = [];
var keys2 = [];
var json1 = { "parentKey" :
{ "childKey" : { "nestedKey" : "value" },
"childKey2": "value2" }};
var json2 = { "parentKey" :
{ "childKey" : { "nestedKey" : "value2",
"nestedKey2": "value3"},
"childKey2": "value2" }};
function getKeys(Obj, res){
res === undefined ? res = [] : 1;
for(prop in Obj){
res.push(prop);
if(Object.prototype.toString.call(Obj[prop]).match(/\s([a-zA-Z]+)/)[1] === "Object"){
getKeys(Obj[prop], res);
}
}
return res;
}
function isDifferent(){
keys1 = getKeys(json1).join("").toLowerCase();
keys2 = getKeys(json2).join("").toLowerCase();
keys1 === keys2 ? alert("SAME") : alert("NOPE");
}
isDifferent();

Related

Create object from multiple object with same value in map JS [duplicate]

I have an array of objects:
[
{ key : '11', value : '1100', $$hashKey : '00X' },
{ key : '22', value : '2200', $$hashKey : '018' }
];
How do I convert it into the following by JavaScript?
{
"11": "1100",
"22": "2200"
}
Tiny ES6 solution can look like:
var arr = [{key:"11", value:"1100"},{key:"22", value:"2200"}];
var object = arr.reduce(
(obj, item) => Object.assign(obj, { [item.key]: item.value }), {});
console.log(object)
Also, if you use object spread, than it can look like:
var object = arr.reduce((obj, item) => ({...obj, [item.key]: item.value}) ,{});
One more solution that is 99% faster is(tested on jsperf):
var object = arr.reduce((obj, item) => (obj[item.key] = item.value, obj) ,{});
Here we benefit from comma operator, it evaluates all expression before comma and returns a last one(after last comma). So we don't copy obj each time, rather assigning new property to it.
This should do it:
var array = [
{ key: 'k1', value: 'v1' },
{ key: 'k2', value: 'v2' },
{ key: 'k3', value: 'v3' }
];
var mapped = array.map(item => ({ [item.key]: item.value }) );
var newObj = Object.assign({}, ...mapped );
console.log(newObj );
One-liner:
var newObj = Object.assign({}, ...(array.map(item => ({ [item.key]: item.value }) )));
You're probably looking for something like this:
// original
var arr = [
{key : '11', value : '1100', $$hashKey : '00X' },
{key : '22', value : '2200', $$hashKey : '018' }
];
//convert
var result = {};
for (var i = 0; i < arr.length; i++) {
result[arr[i].key] = arr[i].value;
}
console.log(result);
I like the functional approach to achieve this task:
var arr = [{ key:"11", value:"1100" }, { key:"22", value:"2200" }];
var result = arr.reduce(function(obj,item){
obj[item.key] = item.value;
return obj;
}, {});
Note: Last {} is the initial obj value for reduce function, if you won't provide the initial value the first arr element will be used (which is probably undesirable).
https://jsfiddle.net/GreQ/2xa078da/
Using Object.fromEntries:
const array = [
{ key: "key1", value: "value1" },
{ key: "key2", value: "value2" },
];
const obj = Object.fromEntries(array.map(item => [item.key, item.value]));
console.log(obj);
A clean way to do this using modern JavaScript is as follows:
const array = [
{ name: "something", value: "something" },
{ name: "somethingElse", value: "something else" },
];
const newObject = Object.assign({}, ...array.map(item => ({ [item.name]: item.value })));
// >> { something: "something", somethingElse: "something else" }
you can merge array of objects in to one object in one line:
const obj = Object.assign({}, ...array);
Use lodash!
const obj = _.keyBy(arrayOfObjects, 'keyName')
Update: The world kept turning. Use a functional approach instead.
Previous answer
Here you go:
var arr = [{ key: "11", value: "1100" }, { key: "22", value: "2200" }];
var result = {};
for (var i=0, len=arr.length; i < len; i++) {
result[arr[i].key] = arr[i].value;
}
console.log(result); // {11: "1000", 22: "2200"}
Simple way using reduce
// Input :
const data = [{key: 'value'}, {otherKey: 'otherValue'}];
data.reduce((prev, curr) => ({...prev, ...curr}) , {});
// Output
{key: 'value', otherKey: 'otherValue'}
More simple Using Object.assign
Object.assign({}, ...array);
Using Underscore.js:
var myArray = [
Object { key="11", value="1100", $$hashKey="00X"},
Object { key="22", value="2200", $$hashKey="018"}
];
var myObj = _.object(_.pluck(myArray, 'key'), _.pluck(myArray, 'value'));
Nearby 2022, I like this approach specially when the array of objects are dynamic which also suggested based on #AdarshMadrecha's test case scenario,
const array = [
{ key : '11', value : '1100', $$hashKey : '00X' },
{ key : '22', value : '2200', $$hashKey : '018' }];
let obj = {};
array.forEach( v => { obj[v.key] = v.value }) //assign to new object
console.log(obj) //{11: '1100', 22: '2200'}
let array = [
{ key: "key1", value: "value1" },
{ key: "key2", value: "value2" },
];
let arr = {};
arr = array.map((event) => ({ ...arr, [event.key]: event.value }));
console.log(arr);
Was did yesterday
// Convert the task data or array to the object for use in the above form
const {clientData} = taskData.reduce((obj, item) => {
// Use the clientData (You can set your own key name) as the key and the
// entire item as the value
obj['clientData'] = item
return obj
}, {});
Here's how to dynamically accept the above as a string and interpolate it into an object:
var stringObject = '[Object { key="11", value="1100", $$hashKey="00X"}, Object { key="22", value="2200", $$hashKey="018"}]';
function interpolateStringObject(stringObject) {
var jsObj = {};
var processedObj = stringObject.split("[Object { ");
processedObj = processedObj[1].split("},");
$.each(processedObj, function (i, v) {
jsObj[v.split("key=")[1].split(",")[0]] = v.split("value=")[1].split(",")[0].replace(/\"/g,'');
});
return jsObj
}
var t = interpolateStringObject(stringObject); //t is the object you want
http://jsfiddle.net/3QKmX/1/
// original
var arr = [{
key: '11',
value: '1100',
$$hashKey: '00X'
},
{
key: '22',
value: '2200',
$$hashKey: '018'
}
];
// My solution
var obj = {};
for (let i = 0; i < arr.length; i++) {
obj[arr[i].key] = arr[i].value;
}
console.log(obj)
You can use the mapKeys lodash function for that. Just one line of code!
Please refer to this complete code sample (copy paste this into repl.it or similar):
import _ from 'lodash';
// or commonjs:
// const _ = require('lodash');
let a = [{ id: 23, title: 'meat' }, { id: 45, title: 'fish' }, { id: 71, title: 'fruit' }]
let b = _.mapKeys(a, 'id');
console.log(b);
// b:
// { '23': { id: 23, title: 'meat' },
// '45': { id: 45, title: 'fish' },
// '71': { id: 71, title: 'fruit' } }

Merging two objects with same keys override first array

I would like to merge an array with another array. The only catch is that each array is within an object.
Intuitively I tried {...arrObj, ...newArrObj} however this leads newArrObj overwriting items in the arrObj.
const array = ['an', 'array'];
const newArray = [, , 'new', 'ehrray'];
const obj = {
key: { ...array
}
};
const newObj = {
key: { ...newArray
}
};
const merged = { ...obj,
...newObj
};
console.log(merged);
I would expect merged to be:
{
"key": {
"0": "an",
"1": "array",
"2": "new",
"3": "ehrray"
}
}
but receive
{
"key": {
"2": "new",
"3": "ehrray"
}
}
This might be useful
const a0 = ['1', '2', undefined , undefined, '5', '6', '7'];
const a1 = [undefined, undefined, '3', '4'];
function merge(a, b) {
return a.map(function(v,i){ return v?v:b[i]});
}
console.log(a0 > a1?merge(a0, a1):merge(a1, a0));
I wanted to updated that I ended up going with a recursive merge to get the nested object containing an array merged.
const array = ['an', 'array'];
const newArray = [, , 'new', 'ehrray'];
const obj = {
key: { ...array
}
};
const newObj = {
key: { ...newArray
}
};
const merge = (obj1, obj2) => {
const recursiveMerge = (obj, entries) => {
for (const [key, value] of entries) {
if (typeof value === "object") {
obj[key] = obj[key] ? { ...obj[key]
} : {};
recursiveMerge(obj[key], Object.entries(value))
} else {
obj[key] = value;
}
}
return obj;
}
return recursiveMerge(obj1, Object.entries(obj2))
}
console.log(merge(obj, newObj));
The idea is that there are unset values with only a few set. eg. const newArray = new Array(4); newArray[2] = 'new';
{ value: null }, even { value: undefined } is not the same thing as { foo: 42 } with no value at all. That's the reason that in your example "an" and "array" are overwritten with the nulls from the newArray.
This particular example you can solve by swapping the order in which you add the arrays to the result, but as soon as both arrays contain null-values there is no way to do it with spread-syntax / Object.assign alone. You have to implement the behaviour:
const array = new Array('an', 'array', null, null, "and", "more", "from", "array");
const newArray = new Array(null, null, 'new', 'ehrray');
function merge(a, b) {
const result = [];
for (let i = 0; i < a.length || i < b.length; ++i) {
result[i] = b[i] == null ? a[i] : b[i];
}
return result;
}
console.log(merge(array, newArray));

How add a new Key/Value pair to a JSON Object?

I have a JS function which should add a key-value pair to a JSON Object.
When the key already exists then it should append the value to the existing key (nested JSON Objects).
Otherwise, it should create the key with the value.
At the moment, sometimes it returns true for the '.hasOwnProperty(key)' method, even when this key doesn't exist.
var myObject= '{}';
function add(key,value){
if(myObject.hasOwnProperty(key)){
var length = Object.keys(myObject[key]).length;
var obj =JSON.parse(myObject);
obj[key] = {};
obj[key][length]= value;
myObject= JSON.stringify(obj);
}
else{
var obj =JSON.parse(myObject);
obj[key] = {};
obj[key]["0"] = value;
myObject= JSON.stringify(obj);
}
}
How the JSON Object should like
myObject = {
"50": {
"0": "value1",
"1": "value2",
},
"51": {
"0": "value3",
"1": "value4",
}
};
Check for existence of a key in an object with the "in" operator
var car = {make: 'Honda', model: 'Accord', year: 1998};
console.log(car);
console.log('make in car: ', 'make' in car);
// expected output: true
delete car.make;
console.log('removed make');
console.log(car);
console.log('add make in again, if not there');
if ('make' in car === false) {
car.make = 'Suzuki';
}
console.log('car.make : ', car.make);
// expected output: "Suzuki"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
Try this:
const addEntry = (myObject, key, value) => ({ ...myObject, [key]: value });
console.log(addEntry({}, "hi", 5)); // { "hi": 5 }
console.log(addEntry({ key: 5 }, "hi", 5)); // { "key": 5, "hi": 5 }
console.log(addEntry({ key: 5 }, "key", 2)); // { "key": 2 }
Try the following code
var myObject= {};
function add(key,value){
myObject.hasOwnProperty(key) ? myObject[key][Object.keys(myObject[key]).length]= value : myObject[key] = {"0": value};
}
add(50, "Hello")
add(50, "World")
add(51, "World")
console.log(myObject)

editing JavaScript object

I have this object:
obj = {key : val,
key1 : val1,
key2 : {key21 : val21,key22 : val22},
key3 : val3}
I want to generate a new object to be like:
objnew = {key : val,
key1 : val1,
key21 : val21,
key22 : val22,
key3 : val3}
As per your comments, if you really want to keep the order for whatever reason, and don't want to do it for anything but key2, here's a possible solution.
Please read this question for information about order of object keys. In short, it's most likely a bad idea to rely on it in most cases. You'd be better off using a Map instance or just an array.
let obj = {
key: 0,
key1: 1,
key2: {key21: 21, key22: 22},
key3: 3
};
let objArray = Object.keys(obj).map(key => ({key, value: obj[key]}));
let result = objArray.reduce((result, entry) =>
Object.assign(result, entry.key === 'key2' ? entry.value : {[entry.key]: entry.value})
, {});
console.log(result);
For 2-level object structure (with Object.keys() and Object.assign() functions):
var obj = {
'key' : 'val',
'key1' : 'val1',
'key2' : {'key21' : 'val21', 'key22' : 'val22'},
'key3' : 'val3'
};
Object.keys(obj).forEach(function(k){
if (typeof obj[k] === 'object') {
Object.assign(obj, obj[k]);
delete obj[k];
}
});
console.log(obj);
Here you go:
var obj = {
key : 1,
key1 : 2,
key2 : { key21 : 3,key22 : 4 },
key3 : 5
};
Object.keys(obj).forEach(function(key) {
if(typeof obj[key] === 'object') {
Object.keys(obj[key]).forEach(function(innerKey) {
obj[innerKey] = obj[key][innerKey];
});
delete obj[key];
}
});
console.log(obj);

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