0

I have an array of objects in angularjs

var list = [{id: 'foo' , value:'bar1'},
 {id: 'foo1' , value:'bar1'}];

I want to add a child object for the first id that equals 'foo'

Formatted JSON Data:

[  
   {  
      "id":'foo',
      "value":'bar1',
      "children":{  
         id:'foo',
         value:'baar'
      }
   },
   {  
      "id":'foo1',
      "value":'bar1'
   }
];

I have tried

var tempList = {id:'foo', value:'baar'};

if(list.id =='foo' )
list.id.children = tempList ;

But its not inserting the value

0

4 Answers 4

1

use map function to add property to object

var list = [
  {id: 'foo' , value:'bar1'},
  {id: 'foo1' , value:'bar1'}
]; 
 

var tempList = {id:'foo', value:'baar'};

list = list.map(function(obj){
  if(obj.id =='foo'){
    obj.children = tempList ;
  }
  
  return obj
})
console.log(list)

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

Comments

0

you have to do it with foreach if you are matching the ids of parent list and child list then use this -

angular.forEach(list , function(value, key){
      if(value.id== tempList.id)
         obj.children = tempList ;
   });

hope it will work

Comments

0

Try this but this will overwrite the id value:

 var list = [{id: 'foo' ,
         value:'bar1'},
        {id: 'foo1' ,
         value:'bar1'}];

 var tempList = {id:'foo', value:'baar'};

 list = list.map(function(obj){

 if(obj.id == 'foo')
 {
   delete obj.id;
   obj.id = {}; 
   obj.id.children = tempList ;
 }

 return obj;
});

console.log(list);

Comments

0

Observation : if(list.id == 'foo') is invalid syntax as list is an array of objects.

So, You can access the id like this list[index].id instead of list.id.

So, to iterate the list array you can use JavaScript for...in loop.

DEMO

var list = [{id: 'foo' , value:'bar1'},
 {id: 'foo1' , value:'bar1'}];
 
 for (var i in list) {
   if(list[i].id =='foo') {
     list[i].children = {  
         id:'foo',
         value:'baar'
      };
   }
 };
 
 console.log(list);

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.