使用香草javascript复制JS对象

时间:2018-08-28 16:48:44

标签: javascript arrays json

我有以下响应数组,我需要将此对象数组转换为json格式,如以下输出所示,所以如何使用纯JavaScript将对象数组转换为json格式。

下面是响应

var data1=[{
       vesrion:v1,
       versionData:[{
            date:'2010',
            value:123
         },{
            date:'2011',
            value:135
         },{
            date:'2012',
            value:145
         }]
      },{
       vesrion:v2,
       versionData:[{
            date:'2010',
            value:223
         },{
            date:'2011',
            value:235
         },{
            date:'2012',
            value:245
         }]
      },{
       vesrion:v3,
       versionData:[{
            date:'2010',
            value:323
         },{
            date:'2011',
            value:335
         },{
            date:'2012',
            value:345
         }]
      }]

================================================ ========================== 必需的对象数组

[{
  date:'2010',
  data:[{
     version:v1,
     value:123
   },{
     version:v2,
     value:223
   },{
     version:v3,
     value:323
   }]
},{
   date:'2011',
  data:[{
     version:v1,
     value:135
   },{
     version:v2,
     value:235
   },{
     version:v3,
     value:335
   }]
},{
    date:'2012',
  data:[{
     version:v1,
     value:145
   },{
     version:v2,
     value:245
   },{
     version:v3,
     value:345
   }] 
}]

}

4 个答案:

答案 0 :(得分:1)

以下代码将为您提供所需的结果:

function a7(data1) {
 var result = [];
 var aa = {};
 var count = data1.length;
 for (var i = 0; i < count; i++) {
  var versionData = data1[i].versionData;
  if (versionData && versionData.length > 0) {
   for (var j = 0; j < versionData.length; j++) {
    var donotAdd = false;
    result.forEach(function(arrayItem) {
     if (arrayItem.date == versionData[j].date)
      donotAdd = true;
    });
    if (!donotAdd) {
     var bb = {};
     aa["date"] = versionData[j].date;
     aa["data"] = [];
     bb["version"] = data1[i].vesrion;
     bb["value"] = versionData[j].value;
     aa["data"].push(JSON.parse(JSON.stringify(bb)));
     for (var p = i; p < count; p++) {
      for (q = 0; q < data1[p].versionData.length; q++) {
       if (data1[p].versionData[q].date == aa["date"] && data1[i].vesrion != data1[p].vesrion) {
        bb = {};
        bb["version"] = data1[p].vesrion;
        bb["value"] = data1[p].versionData[q].value;
        aa["data"].push(JSON.parse(JSON.stringify(bb)));
        break;
       }
      }
      if (p == count - 1) {
       result.push(JSON.parse(JSON.stringify(aa)));
       aa = {};
      }
     }
    }
   }
  }
 }
 return result;
}

答案 1 :(得分:0)

您可以简单地使用Array.reduce()(按日期分组地图)创建地图,并且地图上的Object.values()将为您提供所需的结果:

let data1=[{ vesrion:"v1", versionData:[{ date:'2010', value:123 },{ date:'2011', value:135 },{ date:'2012', value:145 }] },{ vesrion:"v2", versionData:[{ date:'2010', value:223 },{ date:'2011', value:235 },{ date:'2012', value:245 }] },{ vesrion:"v3", versionData:[{ date:'2010', value:323 },{ date:'2011', value:335 },{ date:'2012', value:345 }] }];
      
let result = Object.values(data1.reduce((a, curr)=>{
   if(curr.versionData && curr.versionData.length){
      curr.versionData.forEach((e)=>{
        a[e.date] = a[e.date] || {"date" : e.date};
        (a[e.date].data = a[e.date].data || []).push({version : curr.vesrion, value : e.value});
      });
   }
   return a;
 },{}));
 
console.log(result);

答案 2 :(得分:0)

您可以为此使用简单的forEach并在result object中保存数据日期,并最后使用Object.values(result)获得所需的输出。

var data = [{ vesrion:"v1", versionData:[{ date:'2010', value:123 },{ date:'2011', value:135 },{ date:'2012', value:145 }] },{ vesrion:"v2", versionData:[{ date:'2010', value:223 },{ date:'2011', value:235 },{ date:'2012', value:245 }] },{ vesrion:"v3", versionData:[{ date:'2010', value:323 },{ date:'2011', value:335 },{ date:'2012', value:345 }] }];

var result = {}

data.forEach(v1 => {
    v1.versionData.forEach(v2 => {
        result[v2.date] = result[v2.date] || {
            date: v2.date,
            data: []
        };

        result[v2.date].data.push({
            vesrion: v1.vesrion,
            value: v2.value
        });
    });
});

result = Object.values(result);

console.log(result);

答案 3 :(得分:0)

稍长的答案,对于更广泛的属性来说,灵活性更高:

var sourceData=[{
    version:'v1',
    versionData:[{
        date:'2010',
        value:123
      },{
        date:'2011',
        value:135
      },{
        date:'2012',
        value:145
      }]
  },{
    version:'v2',
    versionData:[{
        date:'2010',
        value:223
      },{
        date:'2011',
        value:235
      },{
        date:'2012',
        value:245
      }]
  },{
    version:'v3',
    versionData:[{
        date:'2010',
        value:323
      },{
        date:'2011',
        value:335
      },{
        date:'2012',
        value:345
      }]
  }
];

transformData = (sourceData) => {
  const ungrouped = ungroup(sourceData, 'version', 'versionData')
  return groupBy(ungrouped, 'date', 'data')
}

ungroup = (sourceData, groupName, itemsName) => {
  const denormalized = sourceData.map( (item) => {
    group = item[groupName]
    subitems = item[itemsName]
    return subitems.map( (subitem) => ({...subitem, [groupName]: group}) )
  })
  return [].concat(...denormalized)
}

groupBy = (ungrouped, groupName, itemsName) => {
  mapped = ungrouped.reduce( (grouped, item) => {
    group = item[groupName]
    clone = { }
    for( propName in item ) {
      if(item.hasOwnProperty(propName) && propName != groupName )
        clone[propName] = item[propName]
    }
    if( !grouped.hasOwnProperty(group) ) {
      grouped[group]={[groupName]:group,[itemsName]:[]}
    }
    grouped[group][itemsName].push(clone)
    return grouped
  }, {})
  return Object.values(mapped)
}

const transformed = transformData(sourceData)
console.log(transformed)