search in JSON tree with full structure intect - javascript

I take this has been asked before here filter nested tree object without losing structure
but what I am looking for is opposite of that.
For the JSON data
var items = [
{
name: "a1",
id: 1,
children: [{
name: "a2",
id: 2,
children: [{
name: "a3",
id: 3
}]
},
{
name: "b2",
id: 5,
children: [{
name: "a4",
id: 4
}]
}]
}
];
We want the filter so that if you search for a2. It should return the following
var items = [
{
name: "a1",
id: 1,
children: [{
name: "a2",
id: 2,
children: [{
name: "a3",
id: 3
}]
}]
}
];
i.e. all the nodes in that tree path (from root to leaf node).
Any idea how to achieve in nodejs/javascript?
Thanks

Follow my example, you can change the code to suit your works:
var items = [
{
name: "a1",
id: 1,
children: [{
name: "a2",
id: 2,
children: [{
name: "a3",
id: 3
}]
},
{
name: "b2",
id: 5,
children: [{
name: "a4",
id: 4
}]
}]
}
];
//console.log(items);
//first, add depth (of each element) to array items
var depths = items;
//structure of path = [[0,length_1st],[1,length_2nd],[2,length_3rd],[3,length_4th],...,[last,length_last]]
var path = [];
//for first value of path
path.push([0,depths.length]);
//test to add depth for depths:
depths.map(function add_depth(current){
current['depth'] = path[path.length-1][0];
if(current.children){
//continue to array children
path.push([path[path.length-1][0]+1,current.children.length]);
current.children.map(add_depth);
}else{
//get back of path
while(path.length>1 && path[path.length-1][1]<2){
path.pop();
}
//decrease length path[...[x,length]]
path[path.length-1][1]--;
};
});
//console.log(depths);
// has depth in array depths, now is function for search in array depths
function search_name(str){
let path_result = [];
let flagExit = false;
depths.findIndex(function find_name(current,index){
if (flagExit){
return;
};
if(current.name===str){
//finish at here
path_result[current.depth] = index;
flagExit = true;
return;
}else{
if(current.children){
path_result[current.depth] = index;
current.children.findIndex(find_name);
};
};
});
return path_result;
};
var name_to_search = "a3";
var path_end = search_name(name_to_search); //console.log(path_end);
//show result from path_end:
var result = [];
var self_items, self_result;
if (path_end){
for(let i=0;i<path_end.length;i++){
if(i===0){
result[i] = {};
result[i]['name'] = items[path_end[i]].name;
result[i]['id'] = items[path_end[i]].id;
if(i === path_end.length-1){
//just the first result
result[i]['children'] = items[path_end[i]].children;
}else{
result[i]['children'] = [];
self_items = items[path_end[i]].children;
self_result = result[i]['children'];
};
}else{
if(i !== path_end.length-1){
//not to the end
self_result[0] = {};
self_result[0]['name'] = self_items[path_end[i]].name;
self_result[0]['id'] = self_items[path_end[i]].id;
self_result[0]['children'] = [];
self_items = self_items[path_end[i]].children;
self_result = self_result[0]['children'];
}else{
//to the end, check for the children end
self_result[0] = {};
self_result[0]['name'] = self_items[path_end[i]].name;
self_result[0]['id'] = self_items[path_end[i]].id;
if(self_items[path_end[i]].children){
self_result[0]['chidren'] = self_items[path_end[i]].children;
};
//check again the searching, if not match the name_to_search, set result to empty!
if(self_result[0]['name'] !== name_to_search){
result = [];
}
};
}
};
}else{
result = [];
}
console.log(result);

The below solution uses object-scan.
Notes: (1) Input is not mutated (2) Well behaved input of form array -> children is expected.
// const objectScan = require('object-scan');
const finder = (name, input) => objectScan(['**(^children$).name'], {
abort: true,
useArraySelector: false,
filterFn: ({ key, value, context, parents }) => {
if (value !== name) {
return false;
}
let cur = context;
for (let idx = 0; idx < key.length - 1; idx += 1) {
const segment = key[idx];
if (idx % 2 === 0) {
cur.push({ ...parents[parents.length - 1 - idx][segment] });
cur = cur[0];
} else {
cur[segment] = [];
cur = cur[segment];
}
}
return true;
}
})(input, []);
const items = [{ name: 'a1', id: 1, children: [{ name: 'a2', id: 2, children: [{ name: 'a3', id: 3 }] }, { name: 'b2', id: 5, children: [{ name: 'a4', id: 4 }] }] }];
console.log(finder('a2', items));
// => [ { name: 'a1', id: 1, children: [ { name: 'a2', id: 2, children: [ { name: 'a3', id: 3 } ] } ] } ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.8.0"></script>
Disclaimer: I'm the author of object-scan

Related

Compare two arrays of objects, and remove if object value is equal

I've tried modifying some of the similar solutions on here but I keep getting stuck, I believe I have part of this figured out however, the main caveat is that:
Some of the objects have extra keys, which renders my object comparison logic useless.
I am trying to compare two arrays of objects. One array is the original array, and the other array contains the items I want deleted from the original array. However there's one extra issue in that the second array contains extra keys, so my comparison logic doesn't work.
An example would make this easier, let's say I have the following two arrays:
const originalArray = [{id: 1, name: "darnell"}, {id: 2, name: "funboi"},
{id: 3, name: "jackson5"}, {id: 4, name: "zelensky"}];
const itemsToBeRemoved = [{id: 2, name: "funboi", extraProperty: "something"},
{id: 4, name: "zelensky", extraProperty: "somethingelse"}];
after running the logic, my final output should be this array:
[{id: 1, name: "darnell"}, {id: 3, name: "jackson5"}]
And here's the current code / logic that I have, which compares but doesn't handle the extra keys. How should I handle this? Thank you in advance.
const prepareArray = (arr) => {
return arr.map((el) => {
if (typeof el === "object" && el !== null) {
return JSON.stringify(el);
} else {
return el;
}
});
};
const convertJSON = (arr) => {
return arr.map((el) => {
return JSON.parse(el);
});
};
const compareArrays = (arr1, arr2) => {
const currentArray = [...prepareArray(arr1)];
const deletedItems = [...prepareArray(arr2)];
const compared = currentArray.filter((el) => deletedItems.indexOf(el) === -1);
return convertJSON(compared);
};
How about using filter and some? You can extend the filter condition on select properties using &&.
const originalArray = [
{ id: 1, name: 'darnell' },
{ id: 2, name: 'funboi' },
{ id: 3, name: 'jackson5' },
{ id: 4, name: 'zelensky' },
];
const itemsToBeRemoved = [
{ id: 2, name: 'funboi', extraProperty: 'something' },
{ id: 4, name: 'zelensky', extraProperty: 'somethingelse' },
];
console.log(
originalArray.filter(item => !itemsToBeRemoved.some(itemToBeRemoved => itemToBeRemoved.id === item.id))
)
Or you can generalise it as well.
const originalArray = [
{ id: 1, name: 'darnell' },
{ id: 2, name: 'funboi' },
{ id: 3, name: 'jackson5' },
{ id: 4, name: 'zelensky' },
];
const itemsToBeRemoved = [
{ id: 2, name: 'funboi', extraProperty: 'something' },
{ id: 4, name: 'zelensky', extraProperty: 'somethingelse' },
];
function filterIfSubset(originalArray, itemsToBeRemoved) {
const filteredArray = [];
for (let i = 0; i < originalArray.length; i++) {
let isSubset = false;
for (let j = 0; j < itemsToBeRemoved.length; j++) {
// check if whole object is a subset of the object in itemsToBeRemoved
if (Object.keys(originalArray[i]).every(key => originalArray[i][key] === itemsToBeRemoved[j][key])) {
isSubset = true;
}
}
if (!isSubset) {
filteredArray.push(originalArray[i]);
}
}
return filteredArray;
}
console.log(filterIfSubset(originalArray, itemsToBeRemoved));
Another simpler variation of the second approach:
const originalArray = [
{ id: 1, name: 'darnell' },
{ id: 2, name: 'funboi' },
{ id: 3, name: 'jackson5' },
{ id: 4, name: 'zelensky' },
];
const itemsToBeRemoved = [
{ id: 2, name: 'funboi', extraProperty: 'something' },
{ id: 4, name: 'zelensky', extraProperty: 'somethingelse' },
];
const removeSubsetObjectsIfExists = (originalArray, itemsToBeRemoved) => {
return originalArray.filter(item => {
const isSubset = itemsToBeRemoved.some(itemToBeRemoved => {
return Object.keys(item).every(key => {
return item[key] === itemToBeRemoved[key];
});
});
return !isSubset;
});
}
console.log(removeSubsetObjectsIfExists(originalArray, itemsToBeRemoved));
The example below is a reusable function, the third parameter is the key to which you compare values from both arrays.
Details are commented in example
const arr=[{id:1,name:"darnell"},{id:2,name:"funboi"},{id:3,name:"jackson5"},{id:4,name:"zelensky"}],del=[{id:2,name:"funboi",extraProperty:"something"},{id:4,name:"zelensky",extraProperty:"somethingelse"}];
/** Compare arrayA vs. delArray by a given key's value.
--- ex. key = 'id'
**/
function deleteByKey(arrayA, delArray, key) {
/* Get an array of only the values of the given key from delArray
--- ex. delList = [1, 2, 3, 4]
*/
const delList = delArray.map(obj => obj[key]);
/* On every object of arrayA compare delList values vs
current object's key's value
--- ex. current obj[id] = 2
--- [1, 2, 3, 4].includes(obj[id])
Any match returns an empty array and non-matches are returned
in it's own array.
--- ex. ? [] : [obj]
The final return is a flattened array of the non-matching objects
*/
return arrayA.flatMap(obj => delList.includes(obj[key]) ? [] : [obj]);
};
console.log(deleteByKey(arr, del, 'id'));
let ff = [{ id: 1, name: 'darnell' }, { id: 2, name: 'funboi' },
{ id: 3, name: 'jackson5' },
{ id: 4, name: 'zelensky' }]
let cc = [{ id: 2, name: 'funboi', extraProperty: 'something' },
{ id: 4, name: 'zelensky', extraProperty: 'somethingelse' }]
let ar = []
let out = []
const result = ff.filter(function(i){
ar.push(i.id)
cc.forEach(function(k){
out.push(k.id)
})
if(!out.includes(i.id)){
// console.log(i.id, i)
return i
}
})
console.log(result)

I need to delete the object list by using matched key. (example the key have 1 and 2 , the result will only show 3)

let selectedRow = ["1","2","3"];
let arr = [
{ id:1, name:"eddie" },
{ id:2, name:"jake" },
{ id:3, name:"susan" },
];
Updation on the answer provided by Andy, If you don't want to update the exiting array and want to result in a new array
let selectedRow = ["1", "2"];
let arr = [
{ id: 1, name: "eddie" },
{ id: 2, name: "jake" },
{ id: 3, name: "susan" },
];
const result = arr.filter(item => !selectedRow.includes(item.id.toString()))
console.log(result)
If you want changes in a current array and don't want to store results in a new array (Not the most efficient solution though)
let selectedRow = ["1", "2"];
let arr = [
{ id: 1, name: "eddie" },
{ id: 2, name: "jake" },
{ id: 3, name: "susan" },
];
for (const row of selectedRow) {
const index = arr.findIndex(item => item.id.toString() === row)
if (index !== -1)
arr.splice(index, 1)
}
console.log(arr)
Make sure your selectedRow array is an array of numbers (because your object ids are numbers).
filter over the array of objects and only keep the ones that selectedRow doesn't include.
const arr = [{ id: 1, name: 'eddie' }, { id: 2, name: 'jake' }, { id: 3, name: 'susan' }];
const selectedRow = ['1', '2'].map(Number);
const result = arr.filter(obj => {
return !selectedRow.includes(obj.id);
});
console.log(result);

How to update Array object index when i delete a array object item from array in angualrjs?

This is my array object
var item = [
{index:1, name: 'miraje'},
{index:2, name: 'alamin'},
{index:3, name: 'behestee'},
{index:4, name: 'arif'},
{index:5, name: 'riad'}
];
when i delete an object like index: 2 , and that time i want to update my index value like ..
var item = [
{ index: 1, name: 'miraje'},
{ index: 2, name: 'behestee'},
{ index: 3, name: 'arif'},
{ index: 4, name: 'riad'}
];
After you remove element you can use forEach() loop to change indexes.
var item = [
{index:1, name: 'miraje'},
{index:2, name: 'alamin'},
{index:3, name: 'behestee'},
{index:4, name: 'arif'},
{index:5, name: 'riad'}
];
item.splice(1, 1)
item.forEach((e, i) => e.index = i + 1)
console.log(item)
Remove the object and alter the index property of each object,
DEMO
i=1;
var item = [
{index:1, name: 'miraje'},
{index:2, name: 'alamin'},
{index:3, name: 'behestee'},
{index:4, name: 'arif'},
{index:5, name: 'riad'}
];
console.log(item);
delete item[ 2 ];
console.log(item);
item.forEach(function(obj) {
obj.index = i;
debugger;
i++;
});
console.log(item);
Basically, you need to find the item with index, delete it, and to update all following items.
function deleteItem(array, index) {
var i = 0, found = false;
while (i < array.length) {
if (found) {
--array[i].index;
++i;
continue;
}
if (found = array[i].index === index) {
array.splice(i, 1);
continue;
}
++i;
}
}
var items = [{ index: 1, name: 'miraje' }, { index: 2, name: 'alamin' }, { index: 3, name: 'behestee' }, { index: 4, name: 'arif' }, { index: 5, name: 'riad' }];
deleteItem(items, 2);
console.log(items);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Just for a variety, without modifying the original array an efficient O(n) approach would also be as follows. We can also provide a range to delete the elements as well...
The range is provided supplied with the array indices, not the object index properties.
var item = [
{index:1, name: 'miraje'},
{index:2, name: 'alamin'},
{index:3, name: 'behestee'},
{index:4, name: 'arif'},
{index:5, name: 'riad'}
];
function deleteObjectsFromArray(a,j,k){
return a.reduceRight((p,c,i) => i >= j && i < k ? p
: i >= k ? (c.index -= k-j, p[c.index-1] = c, p)
: (p[c.index-1] = c, p),[]);
}
console.log(deleteObjectsFromArray(item,2,4));

Merge arrays in JS

Suppose I have the following arrays:
var first = [
{ id: 1, name: 'first' },
{ id: 2, name: 'second' },
{ id: 3, name: 'third' }
]
var second = [
{ id: 2, field: 'foo2' },
{ id: 3, field: 'foo3' },
{ id: 4, field: 'foo4' }
]
var third = [
{ id: 2, data: 'some2' },
{ id: 5, data: 'some5' },
{ id: 6, data: 'some6' }
]
I want to merge them to get the following result:
var result = [
{ id: 1, name: 'first', field: undefined, data: undefined },
{ id: 2, name: 'second', field: 'foo2', data: 'some2' },
{ id: 3, name: 'third', field: 'foo3', data: undefined },
{ id: 4, name: undefined, field: 'foo4', data: undefined },
{ id: 5, name: undefined, field: undefined, data: 'some5' },
{ id: 6, name: undefined, field: undefined, data: 'some6' }
]
How could I do it with JavaScript?
You should get all existed keys and after create new Objects with fill "empty" keys:
function mergeArrays(){
var keys = {};
//save all existed keys
for(var i=arguments.length;--i;){
for(var j=arguments[i].length;--j;){
for(var key in arguments[i][j]){
keys[key] = true;
}
}
}
var res = [];
for(var i=arguments.length;--i;){
for(var j=arguments[i].length;--j;){
//set clone of object
var clone = JSON.parse(JSON.stringify(arguments[i][j]));
for(var key in keys){
if(!(key in clone)){
clone[key] = undefined;
}
}
res.push(clone);
}
}
return res;
}
https://jsfiddle.net/x3b0tk3g/
There is no simple solution for what you want. Here is my suggestion.
var first = [
{ id: 1, name: 'first' },
{ id: 2, name: 'second' },
{ id: 3, name: 'third' }
]
var second = [
{ id: 2, filed: 'foo2' },
{ id: 3, field: 'foo3' },
{ id: 4, field: 'foo4' }
];
var third = [
{ id: 2, data: 'some2' },
{ id: 4, data: 'some4' },
{ id: 6, data: 'some6' }
];
var result = {};
first.concat(second,third).forEach(function(item){
var id = item.id;
var row = result[id];
if(!row){
result[id] = item;
return;
}
for(var column in item){
row[column] = item[column];
}
});
var finalResult = Object.keys(result).map(function(id){
return result[id];
});
console.log(finalResult);
fiddle: http://jsfiddle.net/bs20jvnj/2/
function getByProperty(arr, propName, propValue) {
for (var i = 0; i < arr.length; i++) {
if (arr[i][propName] == propValue) return arr[i];
}
}
var limit = first.length + second.length + third.length;
var res = [];
for (var i = 1; i < limit; i++) {
var x = $.extend({}, getByProperty(first, "id", i), getByProperty(second, "id", i), getByProperty(third, "id", i));
console.log(x["id"]);
if (x["id"] === undefined) x["id"] = i;
res.push(x);
}
console.log(res);
There's probably a shorter way to solve this, but this covers all the steps, including ensuring that there are default properties that are undefined if not found. It also takes any number of input arrays, and you can specify what default keys you require if they're not already covered by the keys in the existing objects, so pretty future-proof for your needs.
// merges the key/values of two objects
function merge(a, b) {
var key;
if (a && b) {
for (key in b) {
if (b.hasOwnProperty(key)) {
a[key] = b[key];
}
}
}
return a;
}
function concatenate() {
var result = [];
var args = arguments[0];
for (var i = 0, l = args.length; i < l; i++) {
result = result.concat(args[i]);
}
return result;
}
// return a default object
function getDefault() {
return {
id: undefined,
name: undefined,
data: undefined,
field: undefined
};
}
// loop over the array and check the id. Add the id as a key to
// a temporary pre-filled default object if the key
// doesn't exist, otherwise merge the existing object and the
// new object
function createMergedArray(result) {
var temp = {};
var out = [];
for (var i = 0, l = result.length; i < l; i++) {
var id = result[i].id;
if (!temp[id]) temp[id] = getDefault();
merge(temp[id], result[i]);
}
// loop over the temporary object pushing the values
// into an output array, and return the array
for (var p in temp) {
out.push(temp[p]);
}
return out;
}
function mergeAll() {
// first concatenate the objects into a single array
// and then return the results of merging that array
return createMergedArray(concatenate(arguments));
}
mergeAll(first, second, third);
DEMO

How do I recursively search an object tree and return the matching object based on a key/value using JavaScript/Prototype 1.7

I've got some nested object data and I want to search it and return the matching object based on the id.
var data = [{id: 0, name: 'Template 0', subComponents:[
{id: 1, name: 'Template 1', subItems:[
{id: 2, name: 'Template 2', subComponents:[{id: 3, name: 'Template 3'}], subItems: [{id: 4, name: 'Template 4'}]}
]}
]}
];
So I want to do something like this
getObjectByKeyValue({id: 3})
and have it return
{id: 3, name: 'Template 3'}
It's sort of got to be done generically because I have subItems, AND subComponents which could each have children.
I tried this using Prototype 1.7 and no luck - I think this just searches an array, and not a tree with it's sub nodes:
data.find(function(s){return s.id == 4;})
Thanks in advance!!!!!!
I went a slightly different route and made the findKey method an Object protype:
Object.prototype.findKey = function(keyObj) {
var p, key, val, tRet;
for (p in keyObj) {
if (keyObj.hasOwnProperty(p)) {
key = p;
val = keyObj[p];
}
}
for (p in this) {
if (p == key) {
if (this[p] == val) {
return this;
}
} else if (this[p] instanceof Object) {
if (this.hasOwnProperty(p)) {
tRet = this[p].findKey(keyObj);
if (tRet) { return tRet; }
}
}
}
return false;
};
Which you would call directly on the data object, passing in the key/value you're looking for:
data.findKey({ id: 3 });
Note that this function allows you to find an object based on any key:
data.findKey({ name: 'Template 0' });
See example → (open console to view result)
Not the best of the and final solution.
But can get you a start for what you are looking...
var data = [{id: 0, name: 'Template 0', subComponents:[
{id: 1, name: 'Template 1', subItems:[
{id: 2, name: 'Template 2', subComponents:[{id: 3, name: 'Template 3'}], subItems: [{id: 4, name: 'Template 4'}]}
]}
]}
];
function returnObject(data,key,parent){
for(var v in data){
var d = data[v];
if(d==key){
return parent[0];
}
if(d instanceof Object){
return returnObject(d,key,data);
};
}
}
function returnObjectWrapper(datavar,key){
return returnObject(datavar,key.id)
}
returnObjectWrapper(data,{id:3})
Please see my solution below or http://jsfiddle.net/8Y6zq/:
var findByKey = function (obj, key) {
var j, key = key || '', obj = obj || {}, keys = key.split("."),
sObj = [], ssObj = [], isSelector = !!(keys.length > 0);
var findKey = function (obj, key) {
var k;
for (k in obj) {
if (k === key) {
sObj.push(obj[k]);
} else if (typeof obj[k] == 'object') {
findKey(obj[k], key);
}
}
};
if (isSelector) {
var nKey = keys.shift();
findKey(obj, nKey);
while (keys.length > 0) {
nKey = keys.shift();
if (sObj.length > 0) {
ssObj = sObj.slice(0), sObj = [];
for (j in ssObj) {
findKey(ssObj[j], nKey);
}
}
}
} else {
findKey(obj, key);
}
// return occurrences of key in array
return (sObj.length === 1) ? sObj.pop() : sObj;
};
var data = [
{id: 0, name: 'Template 0', subComponents: [
{id: 1, name: 'Template 1', subItems: [
{id: 2, name: 'Template 2', subComponents: [
{id: 3, name: 'Template 3'}
], subItems: [
{id: 4, name: 'Template 4'}
]}
]}
]},
{subComponents:{
comp1:'comp1 value',
comp2:'comp2 value',
}}
];
alert(JSON.stringify(findByKey(data, 'subComponents')));
alert(JSON.stringify(findByKey(data, 'subComponents.comp1')));
alert(JSON.stringify(findByKey(data, 'subComponents.comp2')));
In this implementation we can use search by KEY or SELECTOR (eg. "<paren_key>.<child_key_1>.<child_key_2>. ... <child_key_N>")
In case you really need a search through your tree data return all results (not a unique key), here is a little modified version of mVChr's answer:
Object.prototype.findKey = function (keyObj) {
var p, key, val, tRet;
var arr = [];
for (p in keyObj) {
if (keyObj.hasOwnProperty(p)) {
key = p;
val = keyObj[p];
}
}
for (p in this) {
if (p == key) {
if (this[p] == val) {
arr.push(this);
}
} else if (this[p] instanceof Object) {
if (this.hasOwnProperty(p)) {
tRet = this[p].findKey(keyObj);
if (tRet) {
for (var i = 0; i < tRet.length; i++)
arr.push(tRet[i]);
}
}
}
}
if (arr.length > 0)
return arr;
else
return false;
};
We now use object-scan for data processing tasks like this. It's pretty powerful once you wrap your head around how to use it. Here is how you'd answer your questions
// const objectScan = require('object-scan');
const find = (id, input) => objectScan(['**'], {
abort: true,
rtn: 'value',
filterFn: ({ value }) => value.id === id
})(input);
const data = [{ id: 0, name: 'Template 0', subComponents: [{ id: 1, name: 'Template 1', subItems: [{ id: 2, name: 'Template 2', subComponents: [{ id: 3, name: 'Template 3' }], subItems: [{ id: 4, name: 'Template 4' }] }] }] }];
console.log(find(3, data));
// => { id: 3, name: 'Template 3' }
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.8.0"></script>
Disclaimer: I'm the author of object-scan

Categories