Skip to content

Instantly share code, notes, and snippets.

@juanbrujo
Last active September 8, 2015 13:46
Show Gist options
  • Save juanbrujo/54172c9ee21491cce989 to your computer and use it in GitHub Desktop.
Save juanbrujo/54172c9ee21491cce989 to your computer and use it in GitHub Desktop.
mergeObjects: merge array elements according to given certain key/value
// Given this array:
var arr = [
{
"pais": "Chile",
"herramienta": "GTalk, Mailchimp",
"fecha": "ayer"
},
{
"pais": "Argentina",
"herramienta": "JIRA, Mailchimp",
"fecha": "hoy"
},
{
"pais": "Chile",
"herramienta": "Mailchimp, GMail, Asa Na",
"fecha": "hoy"
}
];
// I want to select all values "herramienta" thay belongs to "pais" named "Chile"
function mergeObjects(arr,keyName,keyValue,keyResult){
var items = [];
arr.forEach(function(n){
if( n[keyName] === keyValue ){
item = n[keyResult].replace(/\s/g, '').split(',');
items = items.concat( item );
}
});
return items;
}
console.log( mergeObjects(arr,'pais','Chile','herramienta') );
// result: ["GTalk", "Mailchimp", "Mailchimp", "GMail", "AsaNa"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment