const data = [
{
product_id: 1245,
product_name: "XYZ",
price: "10.00",
batch_number: 1,
},
{
product_id: 12456,
product_name: "RST",
price: "10.00",
batch_number: 1,
},
{
product_id: 111,
product_name: "LMN",
price: "10.00",
batch_number: 2,
},
{
product_id: 222,
product_name: "PQR",
price: "10.00",
batch_number: 2,
},
{
product_id: 456,
product_name: "KKK",
price: "10.00",
batch_number: null,
},
];
我想將此物件格式化為這種型別,并在產品 ID 和產品名稱和價格中添加相同的批號產品。有什么辦法可以解決這個問題。如何將此轉換為 預期輸出 預期輸出
const output = [
{
product_id: "1245, 12345",
product_name: "XYZ, RST",
price: "20.00",
batch_number: 1,
},
{
product_id: "111, 222",
product_name: "LMN, PQR",
price: "20.00",
batch_number: 2,
},
{
product_id: 456,
product_name: "KKK",
price: "10.00",
batch_number: null,
},
];
uj5u.com熱心網友回復:
- 按 屬性對
data陣列進行分組,存盤在 包含鍵值對的Map物件中。batch_number
const map = new Map(data.map(obj=>[obj.batch_number,[]]))
for (let obj of data) {
map.set(obj.batch_number, [...map.get(obj.batch_number)??[],obj]);
}
/*
{1 => [
{
"product_id": 1245,
"product_name": "XYZ",
"price": "10.00",
"batch_number": 1
},
{
"product_id": 12456,
"product_name": "RST",
"price": "10.00",
"batch_number": 1
}
], 2 => Array(2), null => ...}
*/
- 遍歷 map entries()方法中的每個 obj 會回傳一個新的迭代器物件,該物件包含Map物件中每個元素的[key, value]對。
for (let [batch, objs] of map.entries())
object每次迭代都會用一個屬性初始化一個batch_number!每組batch_number獲取他們的product_id、product_name 和price累加價格分別存盤在變數arrValsIds、arrValsNames、prices中。
const object = {
product_id: "",
product_name: "",
price: "",
batch_number: batch,
}
const arrValsIds = [];
const arrValsNames = [];
let prices = 0;
for (let obj of objs) {
arrValsIds.push(obj.product_id);
arrValsNames.push(obj.product_name);
prices = Number(obj.price);
}
- 最后但并非最不重要的一點是,推送到具有 properties 的陣列物件
product_id,并通過使用定點表示法格式化數字的方法product_name加入。', 'totalPricetoFixed()
output.push({
product_id: arrValsIds.join(", "),
product_name: arrValsNames.join(", "),
price: prices.toFixed(2).toString(),
batch_number: batch,
})
預期輸出:
const data = JSON.parse('[{"product_id":1245,"product_name":"XYZ","price":"10.00","batch_number":1},{"product_id":12456,"product_name":"RST","price":"10.00","batch_number":1},{"product_id":111,"product_name":"LMN","price":"10.00","batch_number":2},{"product_id":222,"product_name":"PQR","price":"10.00","batch_number":2},{"product_id":456,"product_name":"KKK","price":"10.00","batch_number":null}]');
const map = new Map(data.map(obj=>[obj.batch_number,[]]))
for (let obj of data) {
map.set(obj.batch_number, [...map.get(obj.batch_number)??[],obj]);
}
const output = [];
for (let [batch, objs] of map.entries()) {
const object = {
product_id: "",
product_name: "",
price: "",
batch_number: batch,
}
const arrValsIds = [];
const arrValsNames = [];
let totalPrice = 0;
for (let obj of objs) {
arrValsIds.push(obj.product_id);
arrValsNames.push(obj.product_name);
totalPrice = Number(obj.price);
}
output.push({
product_id: arrValsIds.join(", "),
product_name: arrValsNames.join(", "),
price: totalPrice.toFixed(2).toString(),
batch_number: batch,
})
}
console.log(output);
uj5u.com熱心網友回復:
下面的代碼片段首先按 對產品進行分類batch_id。然后它結合每個產品中所有產品的資料batch_id。看評論。
const data = [{
product_id: 1245,
product_name: "XYZ",
price: "10.00",
batch_number: 1,
},
{
product_id: 12456,
product_name: "RST",
price: "10.00",
batch_number: 1,
},
{
product_id: 111,
product_name: "LMN",
price: "10.00",
batch_number: 2,
},
{
product_id: 222,
product_name: "PQR",
price: "10.00",
batch_number: 2,
},
{
product_id: 456,
product_name: "KKK",
price: "10.00",
batch_number: null,
},
];
// This is a helper function that creates a key on the map if it doesn't exist
const mapGetOrSet = (map, key, getValue) => {
if (map.has(key)) return map.get(key)
const value = getValue()
map.set(key, value)
return value
}
const transform = data => {
// Use a Map
const productsByBatch = new Map()
// Put each product into a batch
data.forEach(obj => {
const products = mapGetOrSet(productsByBatch, obj.batch_number, () => [])
products.push(obj)
})
// Transform the map into the format the question wants
return [...productsByBatch].map(([batchNumber, products]) => ({
batch_number: batchNumber,
// Get the product_id of all products in the batch and turn them into 1 comma seperated string using Array.prototype.join()
product_id: products.map(({ product_id }) => product_id).join(),
// Same thing as id
product_name: products.map(({ product_name }) => product_name).join(),
price: products
// Turn string into number for addition
.map(({ price }) => parseFloat(price))
// Add every price
.reduce((total, productPrice) => total productPrice)
}))
}
console.log(transform(data))
與輸出格式的唯一區別price是 anumber而不是"25.00".
uj5u.com熱心網友回復:
".reduce()"下面介紹的是實作預期目標的一種可能方式(使用)。
代碼片段
const groupByBatch = arr => (
Object.values( // extract the "values" array from intermediate result obj
arr.reduce( // use ".reduce()" to iterate thru the data
(acc, obj) => { // "acc" is the accumulator / aggregator
// check if batch_number already present in "acc"
let currObj = acc[obj.batch_number] ?? false;
// if found, concat "obj" props to existing ones (ie, "currObj" props)
// else, simply populate "acc" with "obj" props
acc[obj.batch_number] = currObj
? {
product_id: `${currObj.product_id.toString()}, ${obj.product_id.toString()}`,
product_name: `${currObj.product_name}, ${obj.product_name}`,
price: ( currObj.price obj.price).toString(),
batch_number: obj.batch_number
} : {
product_id: obj.product_id.toString(),
product_name: obj.product_name,
price: obj.price,
batch_number: obj.batch_number
};
return acc; // return the accumulator/aggregator "acc"
},
{} // initialize "acc" to empty-object
)
)
);
const data = [{
product_id: 1245,
product_name: "XYZ",
price: "10.00",
batch_number: 1,
},
{
product_id: 12456,
product_name: "RST",
price: "10.00",
batch_number: 1,
},
{
product_id: 111,
product_name: "LMN",
price: "10.00",
batch_number: 2,
},
{
product_id: 222,
product_name: "PQR",
price: "10.00",
batch_number: 2,
},
{
product_id: 456,
product_name: "KKK",
price: "10.00",
batch_number: null,
},
];
console.log('group data by batch: ', groupByBatch(data));
.as-console-wrapper { max-height: 100% !important; top: 0 }
解釋
添加到上述代碼段的行內注釋。
uj5u.com熱心網友回復:
您可以使用 useArray#reduce將陣列轉換為物件,然后Object.entries結合使用Array#map將物件轉換為所需的陣列:
const data = [ { product_id: 1245, product_name: "XYZ", price: "10.00", batch_number: 1 }, { product_id: 12456, product_name: "RST", price: "10.00", batch_number: 1 }, { product_id: 111, product_name: "LMN", price: "10.00", batch_number: 2 }, { product_id: 222, product_name: "PQR", price: "10.00", batch_number: 2 }, { product_id: 456, product_name: "KKK", price: "10.00", batch_number: null } ],
fn = (a,b,r) => a[b] ? {
product_id:`${a[b].product_id} ${r.product_id}`,
product_name:`${a[b].product_name} ${r.product_name}`,
price: ( a[b].price r.price).toFixed(2)
} : r;
output = Object.entries(
data.reduce(
(acc,{batch_number:bn,...r}) =>
({...acc,[bn]:fn(acc,bn,r)}), {}
)
)
.map(([bn,r]) => [ bn || null,r])
.map(
([batch_number, rest]) =>
({...rest, batch_number})
);
console.log( output );
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/469109.html
標籤:javascript 数组 映射减少 减少
