微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 JavaScript 中将对象转换为另一种类型的对象

如何解决在 JavaScript 中将对象转换为另一种类型的对象

我想将从函数获取的对象转换为 Nosql 数据库格式。

我有一个这样的对象:

const data = [ { wineName: "Château Pape-Clément",wineRegion: "Bordeaux (Red)",unitSize: "12x75cl",wineVintage: 2010,qty: 1,totalPrice: 1650,},{ wineName: "Château Beauséjour Duffau-Lagarrosse",unitSize: "6x75cl",totalPrice: 1400,{ wineName: "Vosne-Romanée,Berthaut",wineRegion: "Burgundy (Red)",wineVintage: 2017,totalPrice: 510,{ wineName: "Mazis-ChAmbertin,Faiveley",wineVintage: 2018,totalPrice: 790,{ wineName: "Gevrey-ChAmbertin Les Champeaux,O. Bernstein",unitSize: "3x75cl",wineVintage: 2019,totalPrice: 675,{ wineName: "Latricières-ChAmbertin,J. M. Fourrier",totalPrice: 1050,{ wineName: "Corton Rognet,Taupenot-Merme",totalPrice: 600,{ wineName: "Corton-Charlemagne,Ponsot",wineRegion: "Burgundy (White)",wineVintage: 2012,totalPrice: 980,{ wineName: "Bollinger Grand Année",wineRegion: "Champagne ",wineVintage: 2008,{ wineName: "L'Astre,David Léclapart",wineVintage: 2013,totalPrice: 540,{ wineName: "Brunello di Montalcino Madonna delle Grazie,Marroneto",wineRegion: "Italy ",totalPrice: 945,];

const o = [
  ...data
    .reduce((a,b) => {
      if (a.has(b.wineRegion)) {
        const obj = a.get(b.wineRegion);
        obj.totalPrice += b.totalPrice;
        a.set(b.wineRegion,obj);
      } else {
        a.set(b.wineRegion,{
          wineRegion: b.wineRegion,totalPrice: b.totalPrice,});
      }
      return a;
    },new Map())
    .values(),];

console.log(o);

我创建了如下所示的 Nosql 数据库,现在想将上述对象转换为这样的对象:

{
"visible": true,"active": true,"invalidated": true,"handles": {
    "start": {
        "x": 2094.803738317757,"y": 2038.5794392523367,"highlight": true,"active": false
    },"end": {
        "x": 2487.1775700934586,"y": 2555.364485981309,"active": false,"moving": false
    },"initialRotation": 0,}
}

我找不到解决这个问题的方法

解决方法

在那个用例中,最简单的函数有什么问题吗?我根据您提供的对象作为示例做出了一些假设:您正在对坐标编号进行地板化,并且您希望它们作为新对象中的字符串。

const convertObj = (obj) => {
return {
  visible: {
    BOOL: obj.visible,},active: {
    BOOL: obj.active,handles: {
    M: {
      end: {
        M: {
          active: {
            BOOL: obj.handles.end.active,highlight: {
            BOOL: obj.handles.end.highlight,moving: {
            BOOL: obj.handles.end.moving,x: {
            N: Math.floor(obj.handles.end.x).toString(),y: {
            N: Math.floor(obj.handles.end.y).toString(),initialRotation: {
        N: obj.handles.initialRotation.toString(),start: {
        M: {
          active: {
            BOOL: obj.handles.start.active,highlight: {
            BOOL: obj.handles.start.highlight,x: {
            N: Math.floor(obj.handles.start.x).toString(),y: {
            N: Math.floor(obj.handles.start.y).toString(),};

};

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。