1

I have two separate objects which is shown below

Object1 =  [{value:'A/B'},{value:'A/B/C'},{value:'A/F'},{value:'A/'}];

Object2 =[{option:'A/'},{option:'A/B'}];

Now i need to modify the Object2 by adding a new attribute so that the Object2 must look like this

 Object2 = [{option:'A/',
            directories:[{value:'A/'},{value:'A/B'},{value:'A/B/C'},{value:'A/F'}]},
           {option:'A/B',
            directories:[{value:'A/B'},{value:'A/B/C'},{value:'A/F'},{value:'A/'}]}];

The changes what i need is

  • In directories attribute the first value should be the option value

  • Other values should be the remaining values that should come from Object1

I have tried the following code

angular.forEach(Object2,function(value,key){

 angular.forEach(Object1,function(value,key){

        //I need the code here

  });
});
1
  • I have two separate objects just so you know. it's an array of objects :) Commented Feb 20, 2019 at 6:28

2 Answers 2

1

Try the following

  angular.forEach($scope.Object2,function(value,key){
      value.directories = angular.copy($scope.Object1);
      for (var i=0; i < value.directories.length; i++) {
        if (value.directories[i].value === value.option) {
            var item = value.directories.splice(i,1);  
            value.directories.unshift(item[0]);
            break;
        }
      }
  });

basically after adding the directories array to your object you can find the index of the object that you want in the start of array remove it and add it back to the beginning of the array.

Demo

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

1 Comment

Your out put will be like this [{"option":"A/","directories":[{"value":"A/B"},{"value":"A/B/C"},{"value":"A/F"},{"value":"A/"}]},{"option":"A/B","directories":[{"value":"A/B"},{"value":"A/B/C"},{"value":"A/F"},{"value":"A/"}]}] But actual output what i need is [{"option":"A/","directories":[{"value":"A"},{"value":"A/B/C"},{"value":"A/F"},{"value":"A/B"}]},{"option":"A/B","directories":[{"value":"A/B"},{"value":"A/B/C"},{"value":"A/F"},{"value":"A/"}]}]
0

Why are you iterating twice? You can use just one forEach loop and an arrow function with destructuring:

angular.forEach($scope.Object2, { directories } => directories = $scope.Object1);

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.