使用javascript将数组对象转换为对象数组

时间:2016-06-07 23:28:13

标签: javascript arrays object underscore.js

我有一个大型数组对象。我需要将这个对象分解为一个对象数组。我相信underscore.js是这种类型的对象转换的好工具,但我以前从未使用过该库。对于这个例子,我需要将每个属性的键转换为输出数组中的'name'变量,而不是将每个对象的每个属性的元素推送到数组中。这很难解释,所以我有一个前后阵列来帮助想象我想要完成的事情。我可以使用underscore.js完成此任务比纯javascript更容易吗?我用for循环和if else语句尝试了这个,但它很快就搞乱了,所以任何帮助都非常感谢。

之前:

var obj = {
    "AH5T5TAFXX-001": 
        ["AH5T5TAFXX-001",
        {
            Bin_reads:2436307,
            IC_lot:1,
            LabChip_size_bp:410,
            LibType:"RNA",
            Tot_reads:7386376,
            bioSple:193,
            internal_controls:5
        }, {
            Bin_reads:2906003,
            IC_lot:1,
            LabChip_size_bp:395,
            LibType:"RNA",
            Tot_reads:6680167,
            bioSple:198,
            internal_controls:5
        }],
    "AH5NVVAFXX-002":
        ["AH5NVVAFXX-002",
        {   
            Bin_reads:2436307,
            IC_lot:1,
            LabChip_size_bp:410,
            LibType:"RNA",
            Tot_reads:7386376,
            bioSple:193,
            internal_controls:5
        },
        {   
            Bin_reads:2436307,
            IC_lot:1,
            LabChip_size_bp:410,
            LibType:"RNA",
            Tot_reads:6680167,
            bioSple:193,
            internal_controls:5
        }]
};

之后:

var arr = [
    {
        "name": "AH5T5TAFXX-001",
        "Bin_reads": [2436307,2906003],
        "IC_lot": [1,1],
        "LabChip_size_bp": [410,395],
        "LibType": ["RNA", "RNA"],
        "Tot_reads": [7386376,6680167]
        "bioSple": [193,198],
        "internal_controls": [5,5]
    },{
        "name": "AH5T5TAFXX-002",
        "Bin_reads": [2436307,2906003],
        "IC_lot": [1,1],
        "LabChip_size_bp": [410,395],
        "LibType": ["RNA", "RNA"],
        "Tot_reads": [7386376,6680167]
        "bioSple": [193,198],
        "internal_controls": [5,5]
    }
];

4 个答案:

答案 0 :(得分:1)

// iterate through the keys of 'obj'
// create an array element for each key
console.log( Object.keys(obj).map( function(key){ 

  // 'result' is the element to be returned for each key
  // every property value of 'obj' is an array
  // whose first element represents the name of the new object
  var result = {
    'name': obj[key][0]
  };
  if( obj[key].length > 1 ){
      // pull all attribute names of second element of array
      // and set them to empty arrays in the transformed object
      var properties = Object.keys( obj[key][1] );
      properties.forEach( function( prop ){ result[prop] = []; } );

      // iterate through the input array (skipping the first element)
      // and add a value to the matching array of 'result' 
      for( var i=1; i<obj[key].length; i++ )
        properties.forEach( function( prop ){ result[prop].push( obj[key][i][prop] ); } );
    }
    return result;

}) );

答案 1 :(得分:1)

以下是一种强大的方法,可以展平您的数据结构并合并各个条目。它与条目的数量和顺序无关:

var result = Object.keys(obj).map((key, index) => {
  var entries = obj[key];
  var combined = {};
  entries.forEach(entry => {
    if (typeof entry === 'string') {
       combined.name = entry;
    } else {
      Object.keys(entry).forEach(key => {
        if (Array.isArray(combined[key])) {
          combined[key].push(entry[key]);
        } else {
          combined[key] = [entry[key]];
        }
      });
    }
  });
  return combined;
})

var obj = {
    "AH5T5TAFXX-001": 
        ["AH5T5TAFXX-001",
        {
            Bin_reads:2436307,
            IC_lot:1,
            LabChip_size_bp:410,
            LibType:"RNA",
            Tot_reads:7386376,
            bioSple:193,
            internal_controls:5
        }, {
            Bin_reads:2906003,
            IC_lot:1,
            LabChip_size_bp:395,
            LibType:"RNA",
            Tot_reads:6680167,
            bioSple:198,
            internal_controls:5
        }],
    "AH5NVVAFXX-002":
        ["AH5NVVAFXX-002",
        {   
            Bin_reads:2436307,
            IC_lot:1,
            LabChip_size_bp:410,
            LibType:"RNA",
            Tot_reads:7386376,
            bioSple:193,
            internal_controls:5
        },
        {   
            Bin_reads:2436307,
            IC_lot:1,
            LabChip_size_bp:410,
            LibType:"RNA",
            Tot_reads:6680167,
            bioSple:193,
            internal_controls:5
        }]
};

var result = Object.keys(obj).map((key, index) => {
  var entries = obj[key];
  var combined = {};
  entries.forEach(entry => {
    if (typeof entry === 'string') {
      combined.name = entry;
    } else {
      Object.keys(entry).forEach(key => {
        if (Array.isArray(combined[key])) {
          combined[key].push(entry[key]);
        } else {
          combined[key] = [entry[key]];
        }
      });
    }
  });
  return combined;
})

console.log(result);

答案 2 :(得分:0)

此功能:

function solution(A)
{
    var result = [];
    for (var key in A)
    {
        var subArr = A[key];

        var newObj = {};
        result.push(newObj);
        newObj.name = key;

        for (var i=1, ii=subArr.length; i<ii; i++)
        {
            var subSubObj = subArr[i];
            for (var subSubKey in subSubObj)
            {
                if (!newObj[subSubKey])
                    newObj[subSubKey] = [subSubObj[subSubKey]];
                else
                    newObj[subSubKey].push(subSubObj[subSubKey]);
            }
        }
    }

    return result;
}
如果给出您的输入,

将返回此对象:

[
    {
        "name": "AH5T5TAFXX-001",
        "Bin_reads": [2436307,2906003],
        "IC_lot": [1,1],
        "LabChip_size_bp": [410,395],
        "LibType": ["RNA","RNA"],
        "Tot_reads": [7386376,6680167],
        "bioSple": [193,198],
        "internal_controls": [5,5]
    },
    {
        "name": "AH5NVVAFXX-002",
        "Bin_reads": [2436307,2436307],
        "IC_lot": [1,1],
        "LabChip_size_bp": [410,410],
        "LibType": ["RNA","RNA"],
        "Tot_reads": [7386376,6680167],
        "bioSple": [193,193],
        "internal_controls": [5,5]
    }
]

JSFiddle示例(登录到控制台,所以打开开发工具):https://jsfiddle.net/mpey5wfv/

答案 3 :(得分:0)

以非常直接的方式,它看起来像这样:

// output array
var arr = [];

// iterating the "obj" object
for (prop1 in obj) {

    // temporary object
    var newObj = {
        // setting the property name
        name : prop1,
    };

    // iterating the array of objects
    // skipping the first item. it is a string
    for (var i = 1; i < obj[prop1].length; i++) {

        // iterating the object that's inside the array
        for (prop2 in obj[prop1][i]) {

            // checking if the new property already exists in the new obj
            // if not, create it
            if (!newObj[prop2]) {
                newObj[prop2] = [];
            }

            // adding the values from the two objects into an array in a single object
            newObj[prop2].push(obj[prop1][i][prop2]);
        }
    }
    arr.push(newObj);
}

console.log(JSON.stringify(arr, false, "\t"))输出

[
    {
        "name": "AH5T5TAFXX-001",
        "Bin_reads": [
            2436307,
            2906003
        ],
        "IC_lot": [
            1,
            1
        ],
        "LabChip_size_bp": [
            410,
            395
        ],
        "LibType": [
            "RNA",
            "RNA"
        ],
        "Tot_reads": [
            7386376,
            6680167
        ],
        "bioSple": [
            193,
            198
        ],
        "internal_controls": [
            5,
            5
        ]
    },
    {
        "name": "AH5NVVAFXX-002",
        "Bin_reads": [
            2436307,
            2436307
        ],
        "IC_lot": [
            1,
            1
        ],
        "LabChip_size_bp": [
            410,
            410
        ],
        "LibType": [
            "RNA",
            "RNA"
        ],
        "Tot_reads": [
            7386376,
            6680167
        ],
        "bioSple": [
            193,
            193
        ],
        "internal_controls": [
            5,
            5
        ]
    }
]