javascript - 如何设置规范化数据的数组索引

标签 javascript arrays normalization denormalization

我正在尝试对数据集进行规范化,更新数组索引,然后对数据进行反规范化。

我想更改 P.O.在标题行上并将更改传播到链接的订单。

数据模型如下:

let numSet = 0;
let numLine = 2;

let data = [
  {
    "order": {
      "po_no": "original-po"
    },
    "items": [
      {
        "header": {
          "po_no": "keep-this-value",
          "set_no": 0
        },
        "line": {
          "id": "A123",
          "line_no": 1
        }
      },
      {
        "header": {
          "po_no": "update-with-this-value",
          "set_no": 0
        },
        "line": {
          "id": "B234",
          "line_no": 2
        }
      }
    ]
  }
];

// The logic to normalize the data (appending the order data to each index), works as expected

let normalizedDataSet = [];
for (let i = 0; i < data.length; i++) {
  for (let j = 0; j < data[i]['items'].length; j++) {
    data[i]['items'][j]['order'] = data[i]['order']; // Set default header
    normalizedDataSet.push(data[i]['items'][j]);
  }
}

// The logic to update the normalized data, updating too many indices

for (i = 0; i < normalizedDataSet.length; i++) {
  let index = normalizedDataSet[i];

  if (numSet === index['header']['set_no'] && numLine === index['line']['line_no']) {
    index['order']['po_no'] = index['header']['po_no'];
  }
}

console.log(normalizedDataSet); // Expected output below

预期输出:

normalizedDataSet = [
  { 
    "header": { 
      "po_no": 'keep-this-value', 
      "set_no": 0 
    },
    "line": { 
      "id": 'A123', 
      "line_no": 1 
    },
    "order": { 
      "po_no": 'original-po' 
    } 
  },
  { 
    "header": { 
      "po_no": 'update-with-this-value', 
      "set_no": 0 
    },
    "line": { 
      "id": 'B234', 
      "line_no": 2 
    },
    "order": { 
      "po_no": 'update-with-this-value' 
    } 
  }
]

逐行记录时似乎设置正确,但在第二个 for 循环退出后记录时出现故障。

数据更新后,我想使用原始模式对其进行求助。

我遇到的问题是更新逻辑正在以相同的顺序更改所有条目,而不仅仅是更新单行。 (即,它正在更新 (set_no = 0, line_no = 1)(set_no = 0, line_no = 2),而它应该只更新第二种情况。

在这种情况下,我如何只更新规范化数据集的第二个索引?

最佳答案

我认为问题出在这一行。

data[i]['items'][j]['order'] = data[i]['order']; // Set default header

将此更改为

data[i]['items'][j]['order'] = { ...data[i]['order'] }; // Set default header

原因:在 Javascript 中,对象是通过引用分配的。因此,订单对象在两个项目中都被引用。当您传播它时,它会将属性解压缩到由对象字面量创建的新对象中,进行浅拷贝。

关于javascript - 如何设置规范化数据的数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56563328/

相关文章:

javascript - 使用 TableExport.js 将 HTML 表格导出为 PDF、WORD、PNG

javascript - 使用 WebCrypto API 加密大文件

C# 等效于 C++ map<string,double>

c# - AngularJs $http.post 不渲染新 View

javascript - 如何将跟踪元数据从 python gRPC 服务发送到 grpc-web 客户端?

python - 我应该使用 tf.keras.utils.normalize 来标准化我的目标吗?

sql-server - 数据库设计 : An art or headache (Managing relationships)

PHP - DOMDocument/DOMConfiguration

c++ - BMI计算C++

python - numpy 中的多重对数