How to find a node in a tree with JavaScript - javascript

I have and object literal that is essentially a tree that does not have a fixed number of levels. How can I go about searching the tree for a particualy node and then return that node when found in an effcient manner in javascript?
Essentially I have a tree like this and would like to find the node with the title 'randomNode_1'
var data = [
{
title: 'topNode',
children: [
{
title: 'node1',
children: [
{
title: 'randomNode_1'
},
{
title: 'node2',
children: [
{
title: 'randomNode_2',
children:[
{
title: 'node2',
children: [
{
title: 'randomNode_3',
}]
}
]
}]
}]
}
]
}];

Basing this answer off of #Ravindra's answer, but with true recursion.
function searchTree(element, matchingTitle){
if(element.title == matchingTitle){
return element;
}else if (element.children != null){
var i;
var result = null;
for(i=0; result == null && i < element.children.length; i++){
result = searchTree(element.children[i], matchingTitle);
}
return result;
}
return null;
}
Then you could call it:
var element = data[0];
var result = searchTree(element, 'randomNode_1');

Here's an iterative solution:
var stack = [], node, ii;
stack.push(root);
while (stack.length > 0) {
node = stack.pop();
if (node.title == 'randomNode_1') {
// Found it!
return node;
} else if (node.children && node.children.length) {
for (ii = 0; ii < node.children.length; ii += 1) {
stack.push(node.children[ii]);
}
}
}
// Didn't find it. Return null.
return null;

Here's an iterative function using the Stack approach, inspired by FishBasketGordo's answer but taking advantage of some ES2015 syntax to shorten things.
Since this question has already been viewed a lot of times, I've decided to update my answer to also provide a function with arguments that makes it more flexible:
function search (tree, value, key = 'id', reverse = false) {
const stack = [ tree[0] ]
while (stack.length) {
const node = stack[reverse ? 'pop' : 'shift']()
if (node[key] === value) return node
node.children && stack.push(...node.children)
}
return null
}
This way, it's now possible to pass the data tree itself, the desired value to search and also the property key which can have the desired value:
search(data, 'randomNode_2', 'title')
Finally, my original answer used Array.pop which lead to matching the last item in case of multiple matches. In fact, something that could be really confusing. Inspired by Superole comment, I've made it use Array.shift now, so the first in first out behavior is the default.
If you really want the old last in first out behavior, I've provided an additional arg reverse:
search(data, 'randomNode_2', 'title', true)

My answer is inspired from FishBasketGordo's iterativ answer. It's a little bit more complex but also much more flexible and you can have more than just one root node.
/**searchs through all arrays of the tree if the for a value from a property
* #param aTree : the tree array
* #param fCompair : This function will receive each node. It's upon you to define which
condition is necessary for the match. It must return true if the condition is matched. Example:
function(oNode){ if(oNode["Name"] === "AA") return true; }
* #param bGreedy? : us true to do not stop after the first match, default is false
* #return an array with references to the nodes for which fCompair was true; In case no node was found an empty array
* will be returned
*/
var _searchTree = function(aTree, fCompair, bGreedy){
var aInnerTree = []; // will contain the inner children
var oNode; // always the current node
var aReturnNodes = []; // the nodes array which will returned
// 1. loop through all root nodes so we don't touch the tree structure
for(keysTree in aTree) {
aInnerTree.push(aTree[keysTree]);
}
while(aInnerTree.length > 0) {
oNode = aInnerTree.pop();
// check current node
if( fCompair(oNode) ){
aReturnNodes.push(oNode);
if(!bGreedy){
return aReturnNodes;
}
} else { // if (node.children && node.children.length) {
// find other objects, 1. check all properties of the node if they are arrays
for(keysNode in oNode){
// true if the property is an array
if(oNode[keysNode] instanceof Array){
// 2. push all array object to aInnerTree to search in those later
for (var i = 0; i < oNode[keysNode].length; i++) {
aInnerTree.push(oNode[keysNode][i]);
}
}
}
}
}
return aReturnNodes; // someone was greedy
}
Finally you can use the function like this:
var foundNodes = _searchTree(data, function(oNode){ if(oNode["title"] === "randomNode_3") return true; }, false);
console.log("Node with title found: ");
console.log(foundNodes[0]);
And if you want to find all nodes with this title you can simply switch the bGreedy parameter:
var foundNodes = _searchTree(data, function(oNode){ if(oNode["title"] === "randomNode_3") return true; }, true);
console.log("NodeS with title found: ");
console.log(foundNodes);

FIND A NODE IN A TREE :
let say we have a tree like
let tree = [{
id: 1,
name: 'parent',
children: [
{
id: 2,
name: 'child_1'
},
{
id: 3,
name: 'child_2',
children: [
{
id: '4',
name: 'child_2_1',
children: []
},
{
id: '5',
name: 'child_2_2',
children: []
}
]
}
]
}];
function findNodeById(tree, id) {
let result = null
if (tree.id === id) {
return tree;
}
if (Array.isArray(tree.children) && tree.children.length > 0) {
tree.children.some((node) => {
result = findNodeById(node, id);
return result;
});
}
return result;}

You have to use recursion.
var currChild = data[0];
function searchTree(currChild, searchString){
if(currChild.title == searchString){
return currChild;
}else if (currChild.children != null){
for(i=0; i < currChild.children.length; i ++){
if (currChild.children[i].title ==searchString){
return currChild.children[i];
}else{
searchTree(currChild.children[i], searchString);
}
}
return null;
}
return null;
}

ES6+:
const deepSearch = (data, value, key = 'title', sub = 'children', tempObj = {}) => {
if (value && data) {
data.find((node) => {
if (node[key] == value) {
tempObj.found = node;
return node;
}
return deepSearch(node[sub], value, key, sub, tempObj);
});
if (tempObj.found) {
return tempObj.found;
}
}
return false;
};
const result = deepSearch(data, 'randomNode_1', 'title', 'children');

This function is universal and does search recursively.
It does not matter, if input tree is object(single root), or array of objects (many root objects). You can configure prop name that holds children array in tree objects.
// Searches items tree for object with specified prop with value
//
// #param {object} tree nodes tree with children items in nodesProp[] table, with one (object) or many (array of objects) roots
// #param {string} propNodes name of prop that holds child nodes array
// #param {string} prop name of searched node's prop
// #param {mixed} value value of searched node's prop
// #returns {object/null} returns first object that match supplied arguments (prop: value) or null if no matching object was found
function searchTree(tree, nodesProp, prop, value) {
var i, f = null; // iterator, found node
if (Array.isArray(tree)) { // if entry object is array objects, check each object
for (i = 0; i < tree.length; i++) {
f = searchTree(tree[i], nodesProp, prop, value);
if (f) { // if found matching object, return it.
return f;
}
}
} else if (typeof tree === 'object') { // standard tree node (one root)
if (tree[prop] !== undefined && tree[prop] === value) {
return tree; // found matching node
}
}
if (tree[nodesProp] !== undefined && tree[nodesProp].length > 0) { // if this is not maching node, search nodes, children (if prop exist and it is not empty)
return searchTree(tree[nodesProp], nodesProp, prop, value);
} else {
return null; // node does not match and it neither have children
}
}
I tested it localy and it works ok, but it somehow won't run on jsfiddle or jsbin...(recurency issues on those sites ??)
run code :
var data = [{
title: 'topNode',
children: [{
title: 'node1',
children: [{
title: 'randomNode_1'
}, {
title: 'node2',
children: [{
title: 'randomNode_2',
children: [{
title: 'node2',
children: [{
title: 'randomNode_3',
}]
}]
}]
}]
}]
}];
var r = searchTree(data, 'children', 'title', 'randomNode_1');
//var r = searchTree(data, 'children', 'title', 'node2'); // check it too
console.log(r);
It works in http://www.pythontutor.com/live.html#mode=edit (paste the code)

no BS version:
const find = (root, title) =>
root.title === title ?
root :
root.children?.reduce((result, n) => result || find(n, title), undefined)

This is basic recursion problem.
window.parser = function(searchParam, data) {
if(data.title != searchParam) {
returnData = window.parser(searchParam, children)
} else {
returnData = data;
}
return returnData;
}

here is a more complex option - it finds the first item in a tree-like node with providing (node, nodeChildrenKey, key/value pairs & optional additional key/value pairs)
const findInTree = (node, childrenKey, key, value, additionalKey?, additionalValue?) => {
let found = null;
if (additionalKey && additionalValue) {
found = node[childrenKey].find(x => x[key] === value && x[additionalKey] === additionalValue);
} else {
found = node[childrenKey].find(x => x[key] === value);
}
if (typeof(found) === 'undefined') {
for (const item of node[childrenKey]) {
if (typeof(found) === 'undefined' && item[childrenKey] && item[childrenKey].length > 0) {
found = findInTree(item, childrenKey, key, value, additionalKey, additionalValue);
}
}
}
return found;
};
export { findInTree };
Hope it helps someone.

A flexible recursive solution that will work for any tree
// predicate: (item) => boolean
// getChildren: (item) => treeNode[]
searchTree(predicate, getChildren, treeNode) {
function search(treeNode) {
if (!treeNode) {
return undefined;
}
for (let treeItem of treeNode) {
if (predicate(treeItem)) {
return treeItem;
}
const foundItem = search(getChildren(treeItem));
if (foundItem) {
return foundItem;
}
}
}
return search(treeNode);
}

find all parents of the element in the tree
let objects = [{
id: 'A',
name: 'ObjA',
children: [
{
id: 'A1',
name: 'ObjA1'
},
{
id: 'A2',
name: 'objA2',
children: [
{
id: 'A2-1',
name: 'objA2-1'
},
{
id: 'A2-2',
name: 'objA2-2'
}
]
}
]
},
{
id: 'B',
name: 'ObjB',
children: [
{
id: 'B1',
name: 'ObjB1'
}
]
}
];
let docs = [
{
object: {
id: 'A',
name: 'docA'
},
typedoc: {
id: 'TD1',
name: 'Typde Doc1'
}
},
{
object: {
id: 'A',
name: 'docA'
},
typedoc: {
id: 'TD2',
name: 'Typde Doc2'
}
},
{
object: {
id: 'A1',
name: 'docA1'
},
typedoc: {
id: 'TDx1',
name: 'Typde Doc x1'
}
},
{
object: {
id: 'A1',
name: 'docA1'
},
typedoc: {
id: 'TDx2',
name: 'Typde Doc x1'
}
},
{
object: {
id: 'A2',
name: 'docA2'
},
typedoc: {
id: 'TDx2',
name: 'Type de Doc x2'
}
},
{
object: {
id: 'A2-1',
name: 'docA2-1'
},
typedoc: {
id: 'TDx2-1',
name: 'Type de Docx2-1'
},
},
{
object: {
id: 'A2-2',
name: 'docA2-2'
},
typedoc: {
id: 'TDx2-2',
name: 'Type de Docx2-2'
},
},
{
object: {
id: 'B',
name: 'docB'
},
typedoc: {
id: 'TD1',
name: 'Typde Doc1'
}
},
{
object: {
id: 'B1',
name: 'docB1'
},
typedoc: {
id: 'TDx1',
name: 'Typde Doc x1'
}
}
];
function buildAllParents(doc, objects) {
for (let o = 0; o < objects.length; o++) {
let allParents = [];
let getAllParents = (o, eleFinded) => {
if (o.id === doc.object.id) {
doc.allParents = allParents;
eleFinded = true;
return { doc, eleFinded };
}
if (o.children) {
allParents.push(o.id);
for (let c = 0; c < o.children.length; c++) {
let { eleFinded, doc } = getAllParents(o.children[c], eleFinded);
if (eleFinded) {
return { eleFinded, doc };
} else {
continue;
}
}
}
return { eleFinded };
};
if (objects[o].id === doc.object.id) {
doc.allParents = [objects[o].id];
return doc;
} else if (objects[o].children) {
allParents.push(objects[o].id);
for (let c = 0; c < objects[o].children.length; c++) {
let eleFinded = null;`enter code here`
let res = getAllParents(objects[o].children[c], eleFinded);
if (res.eleFinded) {
return res.doc;
} else {
continue;
}
}
}
}
}
docs = docs.map(d => buildAllParents(d, objects`enter code here`))

This is an iterative breadth first search. It returns the first node that contains a child of a given name (nodeName) and a given value (nodeValue).
getParentNode(nodeName, nodeValue, rootNode) {
const queue= [ rootNode ]
while (queue.length) {
const node = queue.shift()
if (node[nodeName] === nodeValue) {
return node
} else if (node instanceof Object) {
const children = Object.values(node)
if (children.length) {
queue.push(...children)
}
}
}
return null
}
It would be used like this to solve the original question:
getParentNode('title', 'randomNode_1', data[0])

Enhancement of the code based on "Erick Petrucelli"
Remove the 'reverse' option
Add multi-root support
Add an option to control the visibility of 'children'
Typescript ready
Unit test ready
function searchTree(
tree: Record<string, any>[],
value: unknown,
key = 'value',
withChildren = false,
) {
let result = null;
if (!Array.isArray(tree)) return result;
for (let index = 0; index < tree.length; index += 1) {
const stack = [tree[index]];
while (stack.length) {
const node = stack.shift()!;
if (node[key] === value) {
result = node;
break;
}
if (node.children) {
stack.push(...node.children);
}
}
if (result) break;
}
if (withChildren !== true) {
delete result?.children;
}
return result;
}
And the tests can be found at: https://gist.github.com/aspirantzhang/a369aba7f84f26d57818ddef7d108682

Wrote another one based on my needs
condition is injected.
path of found branch is available
current path could be used in condition statement
could be used to map the tree items to another object
// if predicate returns true, the search is stopped
function traverse2(tree, predicate, path = "") {
if (predicate(tree, path)) return true;
for (const branch of tree.children ?? [])
if (traverse(branch, predicate, `${path ? path + "/" : ""}${branch.name}`))
return true;
}
example
let tree = {
name: "schools",
children: [
{
name: "farzanegan",
children: [
{
name: "classes",
children: [
{ name: "level1", children: [{ name: "A" }, { name: "B" }] },
{ name: "level2", children: [{ name: "C" }, { name: "D" }] },
],
},
],
},
{ name: "dastgheib", children: [{ name: "E" }, { name: "F" }] },
],
};
traverse(tree, (branch, path) => {
console.log("searching ", path);
if (branch.name === "C") {
console.log("found ", branch);
return true;
}
});
output
searching
searching farzanegan
searching farzanegan/classes
searching farzanegan/classes/level1
searching farzanegan/classes/level1/A
searching farzanegan/classes/level1/B
searching farzanegan/classes/level2
searching farzanegan/classes/level2/C
found { name: 'C' }

In 2022 use TypeScript and ES5
Just use basic recreation and built-in array method to loop over the array. Don't use Array.find() because this it will return the wrong node. Use Array.some() instead which allow you to break the loop.
interface iTree {
id: string;
children?: iTree[];
}
function findTreeNode(tree: iTree, id: string) {
let result: iTree | null = null;
if (tree.id === id) {
result = tree;
} else if (tree.children) {
tree.children.some((node) => {
result = findTreeNode(node, id);
return result; // break loop
});
}
return result;
}

const flattenTree = (data: any) => {
return _.reduce(
data,
(acc: any, item: any) => {
acc.push(item);
if (item.children) {
acc = acc.concat(flattenTree(item.children));
delete item.children;
}
return acc;
},
[]
);
};
An Approach to convert the nested tree into an object with depth 0.
We can convert the object in an object like this and can perform search more easily.

The following is working at my end:
function searchTree(data, value) {
if(data.title == value) {
return data;
}
if(data.children && data.children.length > 0) {
for(var i=0; i < data.children.length; i++) {
var node = traverseChildren(data.children[i], value);
if(node != null) {
return node;
}
}
}
return null;
}

Related

Get last item active name on the list

How can i have the last item on the list where the case it is success?
children: [
{
case: "no-success",
name: "bruno",
endOffset: 5
},
{
case: "no-success",
name: "pippo",
endOffset: 5
}
{
case: "success",
name: "jo",
endOffset: 5
},
{
case: "success",
name: "Matteo",
endOffset: 5
},
{
case: "np-success",
name: "Robert",
endOffset: 5
}
]
I need to have the item where the name is Matteo.
Example for have the first i do : var foundIdx = this.newListWords[i].children.find(item => item.case === 'success').
Definition:
The find() method returns the FIRST element in the provided array that
satisfies the provided testing function. If no values satisfy the
testing function, undefined is returned.
You can reverse array:
this.newListWords[i].children.reverse().find(item => item.case === 'success')
Or you can use filter and get last child
const filtered = this.newListWords[i].children.filter(item => item.case === 'success')
const lastFind = filtered[filtered.length-1]
function lastSuccess(list: any[]): any {
const SUCCESS_STRING = 'success';
const [lastItem] = list // Take the list's head
.filter(o => o.success === SUCCESS_STRING) // Filter for success
.reverse(); // Reverse the list
return lastItem;
}
const item = lastSuccess(this.newListWords[i].children);
var children = [
{
case: "no-success",
name: "bruno",
endOffset: 5
},
{
case: "no-success",
name: "pippo",
endOffset: 5
},
{
case: "success",
name: "jo",
endOffset: 5
},
{
case: "success",
name: "Matteo",
endOffset: 5
},
{
case: "np-success",
name: "Robert",
endOffset: 5
}
];
function getLastSuccess(children) {
if (!Array.isArray(children)) {
return {};
}
for (var i = children.length - 1, o; o = children[i]; i--) {
if (o.case === 'success') {
return o;
}
}
}
console.log(getLastSuccess(children));
Single line code
let v = children.reduce((s, c) => { if (c.case === "success") { return c } else { return s } }, null);
You will get null if there is no success.
This should find the last item in the filtered array with 'success',
children.findLast(item => item.case === 'success')

How do you get results from within JavaScript's deep object?

expect result: ["human", "head", "eye"]
ex.
const data = {
name: "human",
children: [
{
name: "head",
children: [
{
name: "eye"
}
]
},
{
name: "body",
children: [
{
name: "arm"
}
]
}
]
}
const keyword = "eye"
Using the above data and using ffunction to obtain result
expect_result = f(data)
What kind of function should I write?
Thanks.
You could use an iterative and recursive approach by checking the property or the nested children for the wanted value. If found unshift the name to the result set.
function getNames(object, value) {
var names = [];
[object].some(function iter(o) {
if (o.name === value || (o.children || []).some(iter)) {
names.unshift(o.name);
return true;
}
});
return names;
}
var data = { name: "human", children: [{ name: "head", children: [{ name: "eye" }] }, { name: "body", children: [{ name: "arm" }] }] };
console.log(getNames(data, 'eye'));
console.log(getNames(data, 'arm'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Try a recursive function
const getData = items => {
let fields = [];
for (const item of items) {
if (item.name) {
fields.push(item.name);
}
if (Array.isArray(item.children)) {
fields.push(...getData(item.children));
}
}
return fields;
}
var result = [] // This is outside the function since it get updated
function f(data) {
result.push(data.name); // Add the only name to the Array
if (data.children) { // just checking to see if object contains key children (staying safe)
for (var i = 0; i < data.children.length; i++) { // we are only looping through the children
f(data.children[i]); // Call this particular function to do the same thing again
}
}
}
Basically this function set the name. Then loop through the no of children and then calls a function to set the name of that child and then loop through its children too. Which happen to be a repercussive function till it finishes in order, all of them

Filter object containing array of object

I would like to filter my data depending on a typed keyword.
https://jsfiddle.net/LeoCoco/e96L8akn/
let keyword = '-pre';
let data = {
'Basic': [{
name: 'a-basic'
}, {
name: 'b-basic'
}, {
name: 'c-basic'
}],
'Premium': [{
name: 'a-pre'
}, {
name: 'b-pre'
}, {
name: 'c-pre'
}],
'Extra': [{
name: 'a-ext'
}, {
name: 'b-ext'
}, {
name: 'c-ext'
}],
};
Output
'Premium': [{name: 'a-pre'}, { name: 'b-pre'}, { name: 'c-pre'}]
My try
lodash.forEach(data, (card) => {
card = card.filter(o => {
return Object.keys(o).some(k => {
return typeof o[k] === 'string' && o[k].toLowerCase().includes(keyword.toLowerCase());
});
});
})
But it does not work.The difficulty for me is that the filtering must happen on the nested object keys contained in each array.
var result={};
Object.keys(data).forEach(key => {
result[key] = data[key].filter(o => {
return Object.keys(o).some(k =>typeof o[k] === 'string' && o[k].toLowerCase().includes(keyword.toLowerCase()));
});
})
Because this is object you can use reduce() on Object.keys() instead and then inside use every() to check for keyword.
let keyword = '-pre';
let data = {"Basic":[{"name":"a-basic"},{"name":"b-basic"},{"name":"c-basic"}],"Premium":[{"name":"a-pre"},{"name":"b-pre"},{"name":"c-pre"}],"Extra":[{"name":"a-ext"},{"name":"b-ext"},{"name":"c-ext"}]}
var result = Object.keys(data).reduce(function(r, e) {
var check = data[e].every(o => o.name.indexOf(keyword) != -1);
if(check) r[e] = data[e]
return r;
}, {})
console.log(result)

Filter a dom object of input tags

I am building an object from a form that is currently rendered server side. I collect all the check boxes displayed in the image below and I am trying to sort them in a way that all the check boxes under each step (1, 2, 3 etc) is a single object based on the property parentNode.
Currently the document.querySelectorAll('.checkboxes') fetches all the checkboxes in following format.
var newObj = [
{
name: 'one',
parentNode: {
id: 'stepOne'
}
},
{
name: 'two',
parentNode: {
id: 'stepTwo'
}
},
{
name: 'three',
parentNode: {
id: 'stepOne'
}
},
]
The new object should be:
var newObj = {
stepOne: [
{
name: 'one',
parentNode: {
id: 'stepOne'
}
},
{
name: 'three',
parentNode: {
id: 'stepOne'
}
},
],
stepTwo: [
{
name: 'two',
parentNode: {
id: 'stepTwo'
}
},
]
}
Usually I do something like this:
let stepOne = function(step) {
return step.parentNode.getAttribute('id') === 'stepOne';
}
let stepTwo = function(step) {
return step.parentNode.getAttribute('id') === 'stepTwo';
}
let allTheStepOnes = fetchCheckBoxes.filter(stepOne);
But filter doesn't work on dom object and this seems inefficient as well.
Proper way of doing this is a forEach loop and using associative arrays like this:
let newObject = {};
originalObject.forEach((item)=>{
let step = item.parentNode.id
if (newObj[step] === undefined) {
newObj[step] = []
}
newObj[step].push(item)
})
Using reduce we can reduce your current array into the new structure.
return newObj.reduce(function(acc, item) {
If acc[item.parentNode.id] has been defined before, retrieve this. Otherwise set it to an empty array:
acc[item.parentNode.id] = (acc[item.parentNode.id] || [])
Add the item to the array and then return it:
acc[item.parentNode.id].push(item);
return acc;
We set the accumulator as {} to start with.
Snippet to show the workings.
var newObj = [{
name: 'one',
parentNode: {
id: 'stepOne'
}
}, {
name: 'two',
parentNode: {
id: 'stepTwo'
}
}, {
name: 'three',
parentNode: {
id: 'stepOne'
}
}, ];
var newOrder = function(prevList) {
return prevList.reduce(function(acc, item) {
acc[item.parentNode.id] = (acc[item.parentNode.id] || [])
acc[item.parentNode.id].push(item);
return acc;
}, {});
}
console.log(newOrder(newObj));
This function should do the trick
function mapObj(obj) {
var result = {};
for(var i = 0; i < obj.length; i++) {
var e = obj[i];
result[e.parentNode.id] = result[e.parentNode.id] || [];
result[e.parentNode.id].push(e);
}
return result;
}

How to loop through Array of Objects to find ID then return a sibling key

I have a complex Array of Objects below, and I have a term_id to search on. I'm trying to find the matching term_id, then return the associated ticker: name from the same Object from which I found the term_id.
container = [Object, Object];
// container:
[
0: Object {
tags: [
0: {
term: "tag_name_1",
term_id: 1111
},
0: {
term: "tag_name_2",
term_id: 2222
}
],
ticker: {
name: "ticker1"
}
},
1: Object {
tags: [
0: {
term: "tag_name_3",
term_id: 3333
}
],
ticker: {
name: "ticker2"
}
}
]
How would you accomplish this? Is there an easy way with _lodash?
// You can do this with native JS:
var container = [{tags: [{term: "tag_name_1",term_id: 1111},{term: "tag_name_2",term_id: 2222}],ticker: {name: "ticker1"}},{tags: [{term: "tag_name_3",term_id: 3333}],ticker: {name: "ticker2"}}];
function search (container, id) {
var contains = false;
var result;
container.forEach(function(obj){
obj.tags.forEach(function(innerData){
if (innerData.term_id === id) {
contains = true;
}
})
if (contains) {
result = obj.ticker.name;
contains = false;
}
});
return result;
}
console.log(search(container, 1111));
You can use Array.prototype.some for this. For example:
function find(arr, t) {
var ticker = null;
arr.some(function (doc) {
var tagMatch = doc.tags.some(function (tag) {
return tag.term_id === t;
});
if (tagMatch) {
ticker = doc.ticker.name;
}
return tagMatch;
});
return ticker;
}
Here's a JSFiddle.
Hope this helps you. It's a function that you can pass your objects into and a term_id you search for and it returns found ticker names:
var objs = [
{
tags: [
{
term: "tag_name_1",
term_id: 1111
},
{
term: "tag_name_2",
term_id: 2222
}
],
ticker: {
name: "ticker1"
}
},
{
tags: [
{
term: "tag_name_3",
term_id: 3333
}
],
ticker: {
name: "ticker2"
}
}
];
function getTickerNamesById(objs,id){
var foundNames = [];
objs.forEach(function(obj){
obj.tags.forEach(function(term){
if(term.term_id===id)foundNames.push(obj.ticker.name);
});
});
return foundNames;
}
getTickerNamesById(objs,3333); // ["ticker2"]
A forEach() loop works, though there is no way to prevent it from cycling through the entire object once the id is matched. Assuming the id's are unique, a option with better performance would be the while loop:
function findId(id,container) {
var i = 0,
j;
while (i < container.length) {
j = 0;
while (j < container[i].tags.length) {
if (container[i].tags[j].term_id === id) {
return container[i].ticker.name;
}
j += 1;
}
i += 1;
}
throw "item not found";
}
If your containers will be large you may want to consider this optimization. If you preferred a functional approach, you could accomplish a similar thing with some() or every(), both of which exit out given a specified condition.

Categories

Resources