我與這條資料斗爭,試圖使用javascript轉換它:
[{
rawCol: "personalemail",
template: "CONTACTS",
modifiedCol: "URL"
}, {
rawCol: "personId",
template: "CONTACTS",
modifiedCol: "PERSONCODE"
}, {
rawCol: "ssn",
template: "VITALS",
modifiedCol: "IDENTITY"
}, {
rawCol: "gender",
template: "VITALS",
modifiedCol: "GENDERCODE"
}, {
rawCol: "ethnic",
template: "VITALS",
modifiedCol: "ETHNICCODE"
}, {
rawCol: "birthdate",
template: "VITALS",
modifiedCol: "BIRTHDATE"
}, {
rawCol: "contactType",
template: "OTHER",
modifiedCol: "NETCONTACTTYPE"
}, {
rawCol: "workemail",
template: "OTHER",
modifiedCol: "EMAILADDRESS"
}]
我想創建以下結構:(我想使用上一個 nexted 物件中的唯一模板值,如下所示)
{
CONTACTS: [
{rawFile: "personalemail", modifiedCol: "URL"},
{rawFile: "personId", modifiedCol: "PERSONCODE"}
],
VITALS: [
{rawFile: "ssn", modifiedCol: "IDENTITY"},
{rawFile: "gender", modifiedCol: "GENDERCODE"},
{rawFile: "ethnic", modifiedCol: "ETHNICCODE"},
{rawFile: "birthdate", modifiedCol: "BIRTHDATE"},
],
OTHER: [
{rawFile: "contactType", modifiedCol: "NETCONTACTTYPE"},
{rawFile: "workemail", modifiedCol: "EMAILADDRESS"},]
}
我將非常感謝一個好主意,我可以用一個函式或方法來實作這一點。
uj5u.com熱心網友回復:
const arr = [{
rawCol: "personalemail",
template: "CONTACTS",
modifiedCol: "URL"
}, {
rawCol: "personId",
template: "CONTACTS",
modifiedCol: "PERSONCODE"
}, {
rawCol: "ssn",
template: "VITALS",
modifiedCol: "IDENTITY"
}, {
rawCol: "gender",
template: "VITALS",
modifiedCol: "GENDERCODE"
}, {
rawCol: "ethnic",
template: "VITALS",
modifiedCol: "ETHNICCODE"
}, {
rawCol: "birthdate",
template: "VITALS",
modifiedCol: "BIRTHDATE"
}, {
rawCol: "contactType",
template: "OTHER",
modifiedCol: "NETCONTACTTYPE"
}, {
rawCol: "workemail",
template: "OTHER",
modifiedCol: "EMAILADDRESS"
}];
const data = {};
arr.forEach((ar) => {
data[ar.template] = [...(data[ar.template] || []), {rawFile: ar.rawCol, modifiedCol: ar.modifiedCol}]
});
console.log(data)
uj5u.com熱心網友回復:
所以,你可以試試這個。但是你應該閱讀陣列方法。映射,減少,過濾......
const expectation = data.reduce((res, elem) => {
const val = elem?.template
delete elem.template
if (!res[val]) res[val] = []
res[val].push(elem)
return res
}, {})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/447652.html
標籤:javascript 目的 嵌套的
上一篇:哪個函式更好地覆寫大多數情況,以檢查資料是否在以下2個函式之間是物件
下一篇:如何以另一種方法訪問物件?
