我正在尝试从此javascript映射中按ABC对名字数组进行排序。 我也想从结果中隐藏“未定义”行:
function contacts_callback(obj) {
var contactinfo = obj.contacts.map(o =>
`${o.givenName} ${o.familyName} ${o.organizationName} ${
o.phoneNumbers.map(n => n.phoneNumber)
}`)
.join("<br>");
document.getElementById("demo").innerHTML = contactinfo;
}
// Demo
var obj =
{"success":true,"contacts":[
{"emailAddresses":[],"phoneNumbers":[{"label":"unknown","phoneNumber":"XXX-XXXXXXX"}],"givenName":"GGG","organizationName":"","familyName":"ggg",},
{"emailAddresses":[],"phoneNumbers":[{"label":"unknown","phoneNumber":"XXX-XXXXXXX"}],"givenName":"AAA","organizationName":"","familyName":"aaa",},
{"emailAddresses":[],"phoneNumbers":[{"label":"unknown","phoneNumber":"XXX-XXXXXXX"}],"givenName":"BBB","organizationName":"Apple","familyName":"bbb",},
{"emailAddresses":[],"phoneNumbers":[{"label":"unknown","phoneNumber":"XXX-XXXXXXX"}],"givenName":"undefined","organizationName":"","familyName":"",},
{"emailAddresses":[],"phoneNumbers":[{"label":"unknown","phoneNumber":"XXX-XXXXXXX"}],"givenName":"","organizationName":"Apple","familyName":"",},
]};
contacts_callback(obj);
<div id="demo"></div>
答案 0 :(得分:2)
您可以过滤未定义的名称行,并按givenName
进行排序,然后映射所需的结果。
function contacts_callback(obj) {
var contactinfo = obj.contacts
.filter(({ givenName }) => givenName !== 'undefined')
.sort(({ givenName: a }, { givenName: b }) => a.localeCompare(b))
.map(({ givenName, familyName, organizationName, phoneNumbers }) =>
`${givenName} ${familyName} ${organizationName} ${
phoneNumbers.map(({ phoneNumber }) => phoneNumber)
}`)
.join("<br>");
document.getElementById("demo").innerHTML = contactinfo;
}
// Demo
var obj = { success: true, contacts: [{ emailAddresses: [], phoneNumbers: [{ label: "unknown", phoneNumber: "XXX-XXXXXXX" }], givenName: "GGG", organizationName: "", familyName: "ggg" }, { emailAddresses: [], phoneNumbers: [{ label: "unknown", phoneNumber: "XXX-XXXXXXX" }], givenName: "AAA", organizationName: "", familyName: "aaa" }, { emailAddresses: [], phoneNumbers: [{ label: "unknown", phoneNumber: "XXX-XXXXXXX" }], givenName: "BBB", organizationName: "Apple", familyName: "bbb" }, { emailAddresses: [], phoneNumbers: [{ label: "unknown", phoneNumber: "XXX-XXXXXXX" }], givenName: "undefined", organizationName: "", familyName: "" }, { emailAddresses: [], phoneNumbers: [{ label: "unknown", phoneNumber: "XXX-XXXXXXX" }], givenName: "", organizationName: "Apple", familyName: "" }] };
contacts_callback(obj);
<div id="demo"></div>