代码如下:
var t_tamiStorage = [
{
t_REMARK: "1",
t_SUPPLIER: "",
t_UNIT: "包",
t_binRoom: "A",
t_lotNumber: "00004",
t_materialName: "细胞培养皿",
t_materialNumber: "ZX20230021",
t_putQuantity: "15",
t_specificationModel: "细胞培养皿10个/包",
t_storageLocation: "01-02",
t_validUntil: "2023-05-26"
},
{
t_REMARK: "1",
t_SUPPLIER: "",
t_UNIT: "包",
t_binRoom: "B",
t_lotNumber: "00004",
t_materialName: "细胞培养皿",
t_materialNumber: "ZX20230021",
t_putQuantity: "15",
t_specificationModel: "细胞培养皿10个/包",
t_storageLocation: "01-02",
t_validUntil: "2023-05-26"
}
]
var t_tsliEmpty = [
{
t_REMARK: "王小帅",
t_SUPPLIER: "",
t_UNIT: "包",
t_binRoom: "C",
t_lotNumber: "00002",
t_materialName: "蓝盖试剂瓶",
t_materialNumber: "ZX20230021",
t_putQuantity: "15",
t_specificationModel: "细胞培养皿122个/包",
t_storageLocation: "01-02",
t_validUntil: "2023-05-26"
},
{
t_REMARK: "1",
t_SUPPLIER: "",
t_UNIT: "包",
t_binRoom: "A",
t_lotNumber: "00004",
t_materialName: "细胞培养皿",
t_materialNumber: "ZX20230021",
t_putQuantity: "15",
t_specificationModel: "细胞培养皿10个/包",
t_storageLocation: "01-02",
t_validUntil: "2023-05-26"
}
]
t_binRoom是标识符,现在是想要 A的数据归类在一起, B的数据归类在一起,C的数据归类在一起,A,B,C格式是[{}]
期望将想要 A的数据归类在一起, B的数据归类在一起,C的数据归类在一起,以JSON格式形式,用原生js实现。大佬们,这个该怎么实现呢,谢谢大家
文心一言给出的答案:
var result = {};
Object.keys(t_tamiStorage).forEach(function(key) {
var item = t_tamiStorage[key];
if (!result[item.t_binRoom]) {
result[item.t_binRoom] = [];
}
result[item.t_binRoom].push(item);
});
Object.keys(t_tsliEmpty).forEach(function(key) {
var item = t_tsliEmpty[key];
if (!result[item.t_binRoom]) {
result[item.t_binRoom] = [];
}
result[item.t_binRoom].push(item);
});
if (!Array.prototype.forEach) {
Array.prototype.forEach = function(callback, thisArg) {
var array = this;
for (var i = 0; i < array.length; i++) {
callback.call(thisArg, array[i], i, array);
}
};
}
// 判断 Object.keys 是否可用
if (!Object.keys) {
Object.keys = function(obj) {
if (typeof obj !== "object" && typeof obj !== "function" || obj === null) {
throw new TypeError("Object.keys called on non-object.");
}
var keys = [];
for (var prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
keys.push(prop);
}
}
return keys;
};
}
// 把两个数组合并
var allData = t_tamiStorage.concat(t_tsliEmpty);
var result = allData.reduce((acc, item) => {
if (!acc[item.t_binRoom]) {
acc[item.t_binRoom] = [];
}
acc[item.t_binRoom].push(item);
return acc;
}, {});
// 输出结果
console.log(result);