0

I have the following situation:

var newObject = {user: object, user1: object1}
var user = "something";
var object = {key: [obj, obj], key1: [obj, obj]}

I'd want to add the following to the array of objects in var object:

var addToIt = [objA, objB];

In the end var object should look like:

var object = {key: [obj, obj, objA, objB], key1: [obj, obj]}

I believe there is a way to do it with underscore but until now I've not been able to figure it out. A solution or suggestion would be much appreciated!

In an effort to share my approach, here is something I thought would work but I'm getting an error when I try to push and undefined values for key and key1:

var newHistory = _.mapObject(newObject, function(valN, keyN){
_.mapObject(valN, function(vs, ks){
if(ks = key){
return vs.push(addToIt);
}
})
})
8
  • Where you want to use the underscore ? Commented Jun 4, 2015 at 7:45
  • Will we have access to the keys for var object? Commented Jun 4, 2015 at 7:52
  • 2
    It’s easily possible with object.key=object.key.concat(addToIt); (concat) which makes it a near duplicate of stackoverflow.com/questions/21811184. I’m sure the concat functionality has been covered on StackOverflow before, multiple times. Commented Jun 4, 2015 at 7:53
  • @Mitul, I'd like to underscore as much of it as possible as you can see above. Commented Jun 4, 2015 at 8:30
  • @turnloose, I have access to all keys. Commented Jun 4, 2015 at 8:31

2 Answers 2

1

Try this way and see whether this one works or not

_.mapObject(newObject, function(valN, keyN){

        var arr=[];
        _.mapObject(valN, function(vs, ks){

               if(ks = "key"){
                 arr.push(vs);
                 arr.push(addToIt)

               }
         });
        return arr;
    })
Sign up to request clarification or add additional context in comments.

Comments

0

Here is the solution I found:

var newHistory = _.mapObject(newObject, function(valN, keyN){
if(keyN == key) {
return valN.concat(addToIt);
} else {
return valN;
}
});

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.