const states = ["BR", "UP"];
const template = [
{
"State": "",
"allotment": 25622
},
{
"State": "",
"expenditure": 1254
}
];
let totalRecords: any[] = [];
states.forEach(state=>{
const cc = template.map(record=> {record.State = state; return record})
console.log(state, cc);// here i get the indiviual record set.
totalRecords = totalRecords.concat(cc);
})
console.log(totalRecords);
在這里,我試圖獲得具有不同狀態的模板的串聯串列,但不知何故它覆寫了以前的記錄。盡管在將地圖添加到模板后在控制臺中可以看到,但可以看到正確的記錄集。仍然沒有正確連接。
如何正確執行所需的結果是
[{
"State": "BR",
"allotment": 25622
}, {
"State": "BR",
"expenditure": 1254
}, {
"State": "UP",
"allotment": 25622
}, {
"State": "UP",
"expenditure": 1254
}]
uj5u.com熱心網友回復:
問題是您正在重用來自 的物件template,只是覆寫了這些物件的屬性。如果您想為每個狀態創建多個物件,則需要創建新物件:
const cc = template.map((record) => {
record = { ...record, State: state }; // ***
return record;
});
現場示例:
顯示代碼片段
const states = ["BR", "UP"];
const template = [
{
State: "",
allotment: 25622,
},
{
State: "",
expenditure: 1254,
},
];
let totalRecords /*: any[]*/ = [];
states.forEach((state) => {
const cc = template.map((record) => {
record = { ...record, State: state };
return record;
});
console.log(state, cc);
totalRecords = totalRecords.concat(cc);
});
console.log(totalRecords);
.as-console-wrapper {
max-height: 100% !important;
}
uj5u.com熱心網友回復:
你可以像這樣使用flatMap和map
const states = ["BR", "UP"];
const template = [
{
"State": "",
"allotment": 25622
},
{
"State": "",
"expenditure": 1254
}
];
const totalRecords = states.flatMap(State=> template.map(record=> ({...record, State})))
console.log(totalRecords)
uj5u.com熱心網友回復:
您的程式中的問題出在此處:
template.map(record=> {record.State = state; return record})
您沒有回傳一個新物件,而是覆寫了前一個物件,并且物件參考存盤在陣列中。它們都指向同一個,在記憶體中。
嘗試這個:
const states = ["BR", "UP"];
const template = [
{
"State": "",
"allotment": 25622
},
{
"State": "",
"expenditure": 1254
}
];
let totalRecords: any[] = [];
states.forEach(state=>{
const cc = template.map(record=> ({...record, 'State': state}))
totalRecords = totalRecords.concat(cc);
})
console.log(totalRecords);
這篇文章應該有所幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/492266.html
標籤:javascript 节点.js 数组 级联
上一篇:如何使div中的按鈕居中
