拉取数组对象值,然后推送到另一个数组

nwo49xxi  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(464)

你好我试图循环通过一个对象来执行一个函数,该函数将读取每个分组数组中的每个值,但我一直只保留第一个组。
我试图在数组上迭代并添加push,但未能得到预期的结果。
这是预期的结果,但只返回第一个分组数组。

console.log ->
{
  "order_details": [
    {
      "order_seq": "2104150001"
    },
    {
      "order_seq": "2105110005"
    },
    {
      "order_seq": "2106220007"
    },
    {
      "order_seq": "2105260007"
    }
  ]
}

console.log ->
{
  "order_details": [
    {
      "order_seq": "2105270001"
    }
  ]
}

console.log ->
{
  "order_details": [
    {
      "order_seq": "2104090006"
    },
    {
      "order_seq": "2105060001"
    }
  ]
}

以下是我的脚本片段:

var objectPayload = {
  "0": [{
    "order_seq": "2104150001"
  }, {
    "order_seq": "2105110005"
  }, {
    "order_seq": "2106220007"
  }, {
    "order_seq": "2105260007"
  }],
  "1": [{
    "order_seq": "2105270001"
  }],
  "2": [{
    "order_seq": "2104090006"
  }, {
    "order_seq": "2105060001"
  }]
};

var result = Object.keys(objectPayload).map((key) => objectPayload[key]);

for (let i = 0; i < result.length; i++) {
  var testList = {
    "order_details": []
  };
  setTimeout(function() {
    let jsonSeqNo;
    result[i].map(function(value) {
      jsonSeqNo = {
        'order_seq': value.order_seq
      };
    });
    testList.order_details.push(jsonSeqNo);
    console.log(testList);
  }, i * 500);
}
enyaitl3

enyaitl31#

解决方案非常简单:

var objectPayload = {
  "0": [{
    "order_seq": "2104150001"
  }, {
    "order_seq": "2105110005"
  }, {
    "order_seq": "2106220007"
  }, {
    "order_seq": "2105260007"
  }],
  "1": [{
    "order_seq": "2105270001"
  }],
  "2": [{
    "order_seq": "2104090006"
  }, {
    "order_seq": "2105060001"
  }]
};

const result = Object.values(objectPayload).map((group) => ({
  order_details: group
}));

result.forEach(entry => console.log(entry));

具有 Object.values 您将得到一个组数组。然后使用 Array.prototype.flat 可以展平阵列。

相关问题