我有一个对象数组,看起来像下面的这种结构,我想使用javascript或jquery提取serviceProviderContact字段中的电子邮件,例如mike @ comapny .co.za。目前,我正在使用providerName字段填充下拉列表,但我也想提取电子邮件。
providers: Array(4)
0: {providerId: 1, countryId: 1, providerName: "Vodacom", serviceProviderContact: "support@company.co.za"}
1: {providerId: 2, countryId: 1, providerName: "MTN", serviceProviderContact: "john@company.co.za"}
2: {providerId: 3, countryId: 1, providerName: "Cell C", serviceProviderContact: "mike@company.co.za"}
3: {providerId: 4, countryId: 1, providerName: "Telkom Mobile", serviceProviderContact: "Aplh@company.co.za"}
答案 0 :(得分:0)
您可以使用地图打印电子邮件ID。您必须在每个对象后放置,
,以使其成为有效对象。 Object.values
用于提取数组中对象中存在的所有值
var providers = [{
0: {
providerId: 1,
countryId: 1,
providerName: "Vodacom",
serviceProviderContact: "support@company.co.za"
},
1: {
providerId: 2,
countryId: 1,
providerName: "MTN",
serviceProviderContact: "john@company.co.za"
},
2: {
providerId: 3,
countryId: 1,
providerName: "Cell C",
serviceProviderContact: "mike@company.co.za"
},
3: {
providerId: 4,
countryId: 1,
providerName: "Telkom Mobile",
serviceProviderContact: "Aplh@company.co.za"
}
}]
window.onload=function()
{
var k;
var v;
Object.values(providers[0]).forEach(e=>{
k=document.createElement('option');
v=document.createTextNode(e.providerName);
k.appendChild(v)
document.getElementById('a').appendChild(k)})
}
function a(name)
{
var x=Object.values(providers[0]).filter((e) => e.providerName==name)
alert(x[0].serviceProviderContact)
}
<select id="a" onchange='a(this.value)'>
</select>
答案 1 :(得分:0)
像这样简单地使用map
:
var emails = providers.map(e => e.serviceProviderContact);
演示:
var providers = [{providerId: 1, countryId: 1, providerName: "Vodacom", serviceProviderContact: "support@company.co.za"},
{providerId: 2, countryId: 1, providerName: "MTN", serviceProviderContact: "john@company.co.za"}
{providerId: 3, countryId: 1, providerName: "Cell C", serviceProviderContact: "mike@company.co.za"},
{providerId: 4, countryId: 1, providerName: "Telkom Mobile", serviceProviderContact: "Aplh@company.co.za"}];
var emails = providers.map(e => e.serviceProviderContact);
console.log(emails);