2

I want to find all the dependent of a particular item from an object.

{
   "x": ["a", "b"],
   "a": ["1", "2"],
   "b": [],
   "1": ["abc"],
   "2": [],
   "abc": []
}

Desired output: all the dependencies of items

{
   "x" : ["a", "b", "1", "2", "abc"],
   "a" : ["1", "2", "abc"],
   "1" : ["abc"]
}
12
  • are a, b, and abc variables? Commented Sep 10, 2015 at 6:25
  • nope.. they are just file names Commented Sep 10, 2015 at 6:26
  • Looks like you would need to go through your object and recursively read out the values for each key Commented Sep 10, 2015 at 6:31
  • Without the quotes in the array, it won't work... Now the parser will look for variables like a and b (which I imagine you have not defined separately). Commented Sep 10, 2015 at 6:32
  • 1
    @SpencerWieczorek it seems as though the intention was that a is a string that references the property a on the Object as opposed to a variable a... Commented Sep 10, 2015 at 6:36

2 Answers 2

4

You basically need two functions:

  1. One to loop through your object and find the properties: loopObject
  2. One to resolve your dependencies: getDependencies

For every property in loopObject, getDependencies is called on every item in the array of the property recursively.

In the end, loopObject returns the new object with all the dependencies.

var searchDependencies = {
  "x": ["a", "b"],
  "a": ["1", "2"],
  "b": [],
  "1": ["abc"],
  "2": [],
  "abc": []
};

function loopObject(obj) {
  var resObj = {};
  Object.keys(obj).forEach(function(item) {
    resObj[item] = getDependencies(obj[item], obj);
    if(resObj[item].length < 1) {
        delete resObj[item];
    }
  });

  return resObj;
}

function getDependencies(arr, obj){
  var resArr = arr;
  arr.forEach(function(item) {
    resArr = resArr.concat(getDependencies(obj[item], obj));
  });
  return resArr;
}

var resolvedDependencies = loopObject(searchDependencies);

console.log(resolvedDependencies);

Check out the JSFiddle for a working example.

A word of caution

Watch out that you don't have cyclical dependecies, eg.:

 {
    "a": ["b"],
    "b": ["a"]
 }

Otherwise you will be stuck in an endless loop.

Sign up to request clarification or add additional context in comments.

1 Comment

The solution is inaccurate - "b", "2" & "abc" are not supposed to be in the output.
3

Haven't tested this, but it should be close to what you need to do:

function getDeps(name){
  var deps = arr[name];
  deps.forEach(function(name){
    deps = deps.concat(getDeps(name));
  });
  return deps;
}

You need to search recursively through the array for each filename.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.