lostInTheTetons
lostInTheTetons

Reputation: 1222

How to create a function to add a new array to an object in javascript

I have data coming from the db and I want the user to be able to add a new array after adding the new changes. I want a function that can be used multiple times for different ajax calls.

My object array is var basinSub and the content of the object array is:

{BasinId: (array stuff), SubBasinId: (array stuff), SubBasinName: (array stuff)}

How can I create a for key in data function that I can add a new array to the basinSub object?

I was thinking something like this but it's not working:

function locationChangeData(value, desc) {
    for(var i in basinSub) {
        if(basinSub[i].value == value) {
            basinSub[i].desc = desc;
        }
    }
}

Then I would call the function in the ajax success function:

locationChangeData(basinSub, newSubBasinToAddSub);

Which newSubBasinToAddSub is the new array to add to basinSub.

Upvotes: 1

Views: 63

Answers (1)

JBaldwin
JBaldwin

Reputation: 364

This might do it

    //function to add new changes
    function targetChange(target, source) {
        Object.keys(source).forEach(function(key) {
            for(i=0;i<source.length;i++) {
                target[key][target[key].length++] = source[key][i];
            }
        });
    }

Upvotes: 1

Related Questions