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!
6 Answers 6
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);
}
}
2 Comments
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.
Comments
It seems that you're looking for Object.values.
1 Comment
You can 'foreach' over the object to get it's properties:
for(var j = 0; j < mySet.length; j++)
{
for(var propName in mySet[j])
{
var emailAddress = mySet[j][propName];
// Do Stuff
}
}
4 Comments
Answer for edited question:
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);
The result is kept in ret.
Comments
Is it your input in JSON format? Because if so, it's the wrong syntax. However
let _in = [
{
office : "[email protected]",
home : "[email protected]",
work : "[email protected]",
},
{
home : "[email protected]"
}
]
let _out = []
_in.forEach( record => {
_out = _out.concat(Object.values(record).map(x => new Object({email : x})))
})
console.log(_out)
for each record I extracted values and "packed" into an object with the "email" attrbiute, then I merged all those arrays obtained from the original array of records