Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript. Extract values from associative array

How can I get the values from this associative array in JavaScript?

I just need the email addresses and not the labels.

(
  {
    office = ("[email protected]");
    home = ("[email protected]");
    work = ("[email protected]");
  },
  {
    home = ("[email protected]");
  }
)

UPDATE: Prefered output in JSON would be:

{
    "data": [
        {
            "email": "[email protected]"
        },
        {
            "email": "[email protected]"
        },
        {
            "email": "[email protected]"
        },
        {
            "email": "[email protected]"
        }
    ]
}

Thankful for all input!

like image 362
Jonathan Clark Avatar asked Oct 27 '25 06:10

Jonathan Clark


2 Answers

What you probably meant to do is:

var x = [{
 office: ("[email protected]"),
 home: ("[email protected]"),
 work: ("[email protected]")
},
{
 home: ("[email protected]")
}]

and:

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

// EDIT: however, it's not the best practice to use for … in.

Maybe you could change your data structure to:

var x = [[{
        value: "[email protected]",
        type: "office"
    },
    {
        value: "[email protected]",
        type: "home"
    },
    {
        value: "[email protected]",
        type: "work"
    }],
    [{
        value: "[email protected]",
        type: "home"
    }]];

and iterate over using:

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);
    }
}
like image 170
pawlik Avatar answered Oct 28 '25 20:10

pawlik


Here's a one-liner:

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

where assoc is your associative array.

Edit

I have a better answer here.

like image 41
Sapphire_Brick Avatar answered Oct 28 '25 18:10

Sapphire_Brick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!