gpt4 book ai didi

javascript - 如何在javascript中获取内部数组

转载 作者:行者123 更新时间:2023-12-02 23:57:07 24 4
gpt4 key购买 nike

我正在尝试从数组中获取所有内容。这是提取数据并通过 innerHTML 显示的函数:

window.location.href = 'gonative://contacts/getAll?callback=contacts_callback';

function contacts_callback(obj) {
var contactinfo = obj.contacts.map(({givenName}) => givenName) + " " +
obj.contacts.map(({familyName}) => familyName) + " " + " (" +
obj.contacts.map(({organizationName}) => organizationName) + ") " +
obj.contacts.map(({phoneNumbers.phoneNumber}) => phoneNumbers.phoneNumber) + "<br>";
document.getElementById("demo").innerHTML = contactinfo;
}

这是只有 2 个联系人时输入的示例:

{"success":true,"contacts":[
{
"emailAddresses":[],
"phoneNumbers":
[
{
"label":"unknown",
"phoneNumber":"XXX-XXXXXXX"
}
],
"givenName":"John",
"organizationName":"Apple",
"familyName":"Appleseed",
},
{
"emailAddresses":[],
"phoneNumbers":
[
{
"label":"unknown",
"phoneNumber":"XXX-XXXXXXX"
}
],
"givenName":"John",
"organizationName":"Apple",
"familyName":"Appleseed",
},
]
}

我只想将结果列出为:

John Appleseed (Apple) XXX-XXXXXXX
John Appleseed (Apple) XXX-XXXXXXX

最佳答案

两个问题:

  • 您将显示所有名字,然后是所有姓氏,...等等,每个名字都有一个单独的 .map()称呼。相反,仅执行一项 .map()调用数组,然后显示每个迭代对象的属性。
  • phoneNumbers.phoneNumber不是正确的引用。 phoneNumbers是一个数组,所以你应该迭代它。

另外:

  • 模板文字可能使构建字符串变得更容易
  • 您可以使用.join("<br>")将线条与换行符粘合在一起。

这是更正后的版本:

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":"John","organizationName":"Apple","familyName":"Appleseed",},{"emailAddresses":[],"phoneNumbers":[{"label":"unknown","phoneNumber":"XXX-XXXXXXX"}],"givenName":"John","organizationName":"Apple","familyName":"Appleseed",},]};

contacts_callback(obj);
<div id="demo"></div>

关于javascript - 如何在javascript中获取内部数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55325393/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com