Skip to content Skip to sidebar Skip to footer

How To Merge Two Objects In Javascript

I would like to merge objects here and would like to convert to JSON object. I would like to create an object array and add objects in to it. In this example i would like to create

Solution 1:

var dataArray = [], i;

for(i = 0; i < dataset.length; i++)
{
    dataArray.push({
        "name":         dataset[x].repository,
        "region":       dataset[x].BusinessUnit,
        "checkins":     [index, dataset[x].AvgCheckinCount],
        "teamsize":     [index, dataset[x].TeamSize],
        "Checkintimes": [index, dataset[x].MeanBuildTimeHrs]
    });
}

console.log(JSON.stringify(dataArray));

You need to use a new object for every element in your array. Objects are stored by reference, and variables have function scope.

After having a look at your other questions, I recommend you to have a look at the JavaScript guide.

Solution 2:

Can you use lodash?

var names = {
  'characters': [
    { 'name': 'barney' },
    { 'name': 'fred' }
  ]
};

var ages = {
  'characters': [
    { 'age': 36 },
    { 'age': 40 }
  ]
};

_.merge(names, ages);
// → { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] }

var food = {
  'fruits': ['apple'],
  'vegetables': ['beet']
};

var otherFood = {
  'fruits': ['banana'],
  'vegetables': ['carrot']
};

_.merge(food, otherFood, function(a, b) {
  return_.isArray(a) ? a.concat(b) : undefined;
});
// → { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] }

Post a Comment for "How To Merge Two Objects In Javascript"