从两个不同数组中的对象创建对象

时间:2016-02-27 17:03:38

标签: javascript jquery arrays javascript-objects

我有两个不同的对象数组。两个数组中的对象具有不同的属性。我想通过两个数组并获取我想要的属性,然后使用组合属性创建一个新对象。我似乎无法弄清楚如何做到这一点。这是我到目前为止所拥有的。

所以基本上。

array1中的对象有两个我需要的属性。轮辋和关节

array2中的对象有一个我需要的属性。属性

我想构建一个新对象,使其具有边缘,关节和属性。

var projectWheel = {};

var wheels = [
    {
        property1: value,
        property2: value,
        joints: [],
        rim: {
            property1: value
        }
    },
    {
        property1: value,
        property2: value,
        joints: [],
        rim: {
            property1: value
        }
    }
];

var virtualMachines = [
    {
        property1: value,
        property2: value,
        property3: value,
        attributes: {
            property: value
        }
    },
    {
        property1: value,
        property2: value,
        property3: value,
        attributes: {
            property: value
        }
    }
];

var ExportVM = function (wheel, virtualmachine) {
    var SpokeVM;
    var newSpoke;
    var commonArray = [];

    projectWheel.spokes = [];

    SpokeVM = function (vm, spoke) {
        // data here
    }

    $.each(wheel.spokes, function (key, spoke) {
        commonArray.push(spoke);
    });

    $.each(virtualmachine, function (key, vm) {
        commonArray.push(vm);
    });

    $.each(commonArray, function (key, data) {
        var spoke;
        var virtualmachine;

        if (data.rim) spoke = data;
        if (data.attributes) virtualmachine = data;

        newSpoke = new SpokeVM(virtualmachine, spoke);
        projectWheel.spokes.push(newSpoke);
    });
}

ExportVM(wheels, virtualMachines);

要创建的预期对象

{
    attributes: {
        property1: value
    },
    rim: {
        property1: value
    },
    joints: []
}

1 个答案:

答案 0 :(得分:1)

这是我的解决方案。

var requiredProperties = ["attributes","rim","joints"]  //set all the required properties that you want to retrieve

function GetProcessedObjectArray(wheels,virtualMachines,requiredProperties){
   var arraySize = wheels.length;
   var finalArray =[];

   $.each(wheels,function(i,v){
     var currObj = {};
     $.each(wheels[i],function(key,value){
        if ( $.inArray(key, requiredProperties) > -1 ) {
          currObj[key] = value;
        }
     });
      $.each(virtualMachines[i],function(key,value){
        if ( $.inArray(key, requiredProperties) > -1 ) {
          currObj[key] = value;
        }
     });
     finalArray.push(currObj);
   });  

   return finalArray;
}


console.log(GetProcessedObjectArray(wheels,virtualMachines,requiredProperties));

查看此Working JsFiddle