0

I have wrote for the given data of code,but unable to combined for the one array of objects into another array of objects like as given below.

    var data=[{x:10,y:30},{a:50,b:40}]
    var data1=[{x1:10,y1:30},{a1:50,b1:40}]

    function fctnCombind(){
    for(var i in data){
    for(var j in data1){
    data[i].children=data1[j]
    //console.log(data[i].children)
    data[i].push(data[i].children)
    }
    return data;
    }

    }
And final output is given below:
        [{x:10,y:30,c:[x1:10,y1:30]},{a:50,b:40,d:[a1:50,b1:40]}]
bobby k
  • 11
  • 3

2 Answers2

0

As per your code,

When you're iterating the arrays. You are storing array2 first item in .children property of array1[i] which is an object.

Now when you use data[i].push(data[i].children), as data[i] is actually an object, it doesn't have push property. So it fails.

Assuming that the order is maintained.

var data = [{
    x: 10,
    y: 30
}, {
    a: 50,
    b: 40
}]
var data1 = [{
    x1: 10,
    y1: 30
}, {
    a1: 50,
    b1: 40
}];


function combineObjects(data, data1) {
    for(var i=0; i < data.length; i++) {
        Object.keys(data1[i]).forEach(function(item) {
           data[i][item] = data1[i][item] 
        });
    }
    return data;
}

   combineObjects(data, data1);
mohamedrias
  • 18,326
  • 2
  • 38
  • 47
  • You didn't run the code, did you? The result is `[{"x":10,"y":30,"x1":10,"y1":30,"a1":50,"b1":40},{"a":50,"b":40,"x1":10,"y1":30,"a1":50,"b1":40}]`. – Felix Kling Mar 28 '15 at 05:57
0

You really just have to iterate over one of the arrays and do what is described in How can I merge properties of two JavaScript objects dynamically?:

    var data = [{x:10,y:30},{a:50,b:40}];
    var data1 = [{x1:10,y1:30},{a1:50,b1:40}];

    // copy
    var result = data.map(function(value, i) {
        return Object.assign({}, value, data1[i]);
    });
    console.log(result);

    // in place
    data.forEach(function(value, i) {
      for (var prop in data1[i]) {
          value[prop] = data1[i][prop];
      }
    });
    // `data` is now the merged result
    console.log(data);
    

This assumes that both arrays are of the same length.

Polyfill for Object.assign.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143