I have a data object with each object containing a tags array, I would like to loop through the object and grab each of the object tags and combine eventually combine the values into 1 array called selections on completion of the loop. At the moment however I'm unable to solve this, I have tried pushing the tags into an array then use the underscore _.union method and also tries concatenating each looped array into 1 but with no success. Can anyone recommend a solution?
Fiddle: http://jsfiddle.net/24qh7zfv/3/
JS
var selection = [];
var data = ([
{
role: "Developer",
tag: "developer",
tags: ["Javascript", "CSS", "HTML"]
}, {
role: "Producer",
tag: "producer",
tags: ["Project Management", "Pitching", "Billing"]
}
]);
for( var i = 0, len = data.length; i < len; i++ ) {
selection.concat(data[i].tags);
}
console.log(selection);
4 Answers 4
You need to reassign selection, and concat to tho that. so use:
for( var i = 0, len = data.length; i < len; i++ ) {
selection = selection.concat(data[i].tags);
}
Comments
This should work.
var selection = [];
var data = [
{
role: "Developer",
tag: "developer",
tags: ["Javascript", "CSS", "HTML"]
}, {
role: "Producer",
tag: "producer",
tags: ["Project Management", "Pitching", "Billing"]
}
];
for( var i = 0; i < data.length; i++ ) {
for(var j = 0; j < data[i].tags.length; j++){
selection.push(data[i].tags[j]);
}
}
Comments
You can simply do this.
var selection = data.map(function(x){
return x.tags;
}).join().split(",");
Comments
i think better use concat array function . see concat function in http://skillgun.com/javascript/arrays/tutorial