的JavaScript。从关联数组中提取值

时间:2011-04-19 18:44:03

标签: javascript arrays

如何在Javascript中从此关联数组中获取值? 我只需要电子邮件地址而不是标签。

(
{
 office = ("my@email.com");
 home = ("ahome@anotheremail.com");
 work = ("nothing@email.com");
},
{
 home = ("test@test.se");
}
)

更新:JSON中的首选输出为:

{
    "data": [
        {
            "email": "my@email.com"
        },
        {
            "email": "ahome@anotheremail.com"
        },
        {
            "email": "nothing@email.com"
        },
        {
            "email": "test@test.se"
        }

] }

感谢所有输入!

6 个答案:

答案 0 :(得分:4)

你可能想做的是:

var x = [{
 office: ("my@email.com"),
 home: ("ahome@anotheremail.com"),
 work: ("nothing@email.com")
},
{
 home: ("test@test.se")
}]

for(var j = 0; j < x.length; j++)
{
    for(var anItem in x[j])
    {
        console.log(x[j][anItem])
    }
}

//编辑: 但是,it's not the best practice用于... in。

也许您可以将数据结构更改为:

var x = [[{
        value: "my@email.com",
        type: "office"
    },
    {
        value: "ahome@anotheremail.com",
        type: "home"
    },
    {
        value: "nothing@email.com",
        type: "work"
    }],
    [{
        value: "test@test.se",
        type: "home"
    }]];

并迭代使用:

for( var i = 0, xlength = x.length; i < xlength; i++ )
{
    for( var j=0, ylength = x[i].length; j < ylength; j++ )
    {
        console.log(x[i][j].value);
    }
}

答案 1 :(得分:1)

你可以'foreach'对象来获取它的属性:

for(var j = 0; j < mySet.length; j++)
{
    for(var propName in mySet[j])
    {
        var emailAddress = mySet[j][propName];
        // Do Stuff
    }
}

答案 2 :(得分:0)

回答编辑过的问题:

var ret = {data: []};

for(var j = 0; j < x.length; j++)
{
    for(var anItem in x[j])
    {
        ret.data.push({
            email: x[j][anItem]
        });
    }
}

console.log(ret);

结果保存在ret

答案 3 :(得分:0)

这里是单线:

console.log(Object.keys(assoc).map(k => assoc[k]));

其中var assoc = // your associative array

答案 4 :(得分:0)

您是以JSON格式输入的吗?因为如果是这样,那是错误的语法。但是

let _in = [
 {
   office : "my@email.com",
   home : "ahome@anotheremail.com",
   work : "nothing@email.com",
 },
 {
   home : "test@test.se"
 }
]

let _out = []
_in.forEach( record => {  
   _out =  _out.concat(Object.values(record).map(x => new Object({email : x})))
})

console.log(_out)

对于每条记录,我提取值并将其“打包”到带有“电子邮件”属性的对象中,然后合并从原始记录数组中获得的所有那些数组

答案 5 :(得分:0)

您似乎正在寻找Object.values

相关问题