动态创建对象数组

时间:2018-08-22 06:42:00

标签: javascript arrays

我有2个数组

var data=["a|b|c",
           "d|e|f",
           "g||i",
           "||l"];

var column=[{col:"column1"},
            {col:"column2"},
            {col:"column3"}]//dynamic, can sometimes be up to 10 columns

如何基于这两个对象动态创建对象数组? 例如,输出应如下所示:

var newArray =[{column1:"a",column2:"b",column3:"c"},
               {column1:"d",column2:"e",column3:"f"},
               {column1:"g",column2:"",column3:"i"},
               {column1:"",column2:"",column3:"l"}]

3 个答案:

答案 0 :(得分:3)

您可以映射data并拆分新键/值对的值,并采用单个对象进行映射。

var data = ['a|b|c', 'd|e|f', 'g||i', '||l'],
    columns = [{ col: "column1" }, { col: "column2" }, { col: "column3" }],
    result = data.map(s =>
        Object.assign(...s.split('|').map((v, i) => ({ [columns[i].col]: v }))));
    
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- end snippet -->

var data = 'a|b|c,d|e|f,g||i,||l'
result = data.split(',').map(function(l, i) {
  var tmp = {}
  l.split('|').forEach(function(t, j) {
    var key = 'column' + (j + 1)
    tmp[key] = t
  })
  return tmp
})
console.log(result);
var data = 'a||'
result = data.split(',').map(function(l, i) {
  var tmp = {}
  l.split('|').forEach(function(t, j) {
    var key = 'column' + (j + 1)
    if (t)
      tmp[key] = t
  })
  return tmp
})
console.log(result);

答案 2 :(得分:0)

var data = 'a|b|c,d|e|f,g||i,||l'
result = data.split(',').map(function(l, i) {
  var tmp = {}
  l.split('|').forEach(function(t, j) {
    var key = 'column' + (j + 1)
    tmp[key] = t
  })
  return tmp
})
console.log(result);
var data = 'a||'
result = data.split(',').map(function(l, i) {
  var tmp = {}
  l.split('|').forEach(function(t, j) {
    var key = 'column' + (j + 1)
    if (t)
      tmp[key] = t
  })
  return tmp
})
console.log(result);