javascript - 将对象数组转换为不同结构对象的数组

标签 javascript arrays

我的问题可能很简单,但我的眼睛在眨,我现在想不出别的东西。任何帮助表示赞赏

这是我的初始数组

var Products = [
   {
     "order_product_id":"1111", 
     "order_id":"555", 
     "product_id":"111", 
     "name":"name1", 
     "model":"111", 
     "quantity":"1", 
     "price":"100", 
     "total":"100", 
     "tax":"20",
   },
   {      
     "order_product_id":"2222",    
     "order_id":"555",      
     "product_id":"222",      
     "name":"name2",      
     "model":"222",      
     "quantity":"1",      
     "price":"200",      
     "total":"200",      
     "tax":"40",      

   }
];

这是我需要的数组(更改名称并排除一些元素)

{
      "id": "1111",
      "name": "name1",
      "category": "",
      "list_position": 1,
      "quantity": 1,
      "price": '100'
    },
    {
      "id": "2222",
      "name": "name2",
      "category": " ",
      "list_position": 2,
      "quantity": 1,
      "price": '200'
    }

最后这是我想在操作后放置新产品阵列的地方

   {
    "transaction_id": 1,
    "value": 99,
    "currency": "EUR",
    "shipping": 0,
    "items": Items
   }

我试过 push/forEach/even string 但我无法像 Google 想要的那样得到一个最终的干净数组

gtag('event', 'purchase', {
  "transaction_id": 1,
  "value": 99,
  "currency": "EUR",
  "shipping": 0,
  "items": [
    {
      "id": "1111",
      "name": "name1",
      "category": "",
      "list_position": 1,
      "quantity": 1,
      "price": '100'
    },
    {
      "id": "2222",
      "name": "name2",
      "category": " ",
      "list_position": 2,
      "quantity": 1,
      "price": '200'
    }
  ]
});

最佳答案

您可以创建自己的方法来构建对象并使用 Array.prototype.map 进行迭代。

var Products = [
  {
    order_product_id: "1111",
    order_id: "555",
    product_id: "111",
    name: "name1",
    model: "111",
    quantity: "1",
    price: "100",
    total: "100",
    tax: "20"
  },
  {
    order_product_id: "2222",
    order_id: "555",
    product_id: "222",
    name: "name2",
    model: "222",
    quantity: "1",
    price: "200",
    total: "200",
    tax: "40"
  }
];

let getObj = (obj, i) => ({
  id: obj.order_product_id,
  name: obj.name,
  category: obj.category || "",
  list_position: i + 1,
  quantity: obj.quantity,
  price: obj.price
});

let Items = Products.map(getObj);
console.log(Items);

关于javascript - 将对象数组转换为不同结构对象的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58436126/

相关文章:

arrays - 如何使用 TableView 获取数组中所选值的 Int?

c - 如何在 C 函数中使用全局结构引用填充结构指针?

ios - 对 X 和 Y 顶点数组进行排序? iOS/Objective-C

arrays - 如何将结构数组切片成行,而不是列?

javascript - .attr ('href' )返回未定义

javascript - YouTube上的Wonder Plugin Carousel多个播放列表请求崩溃

javascript - html5 中全宽视频大于屏幕尺寸

javascript - 输入类型单选按钮已选中 else 语句在 jquery 中不起作用

javascript - webpack require (jquery) 不起作用

javascript - window.prompt 定义的嵌套数组不使用 .innerHTML 更新 View