0

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);
asked Oct 10, 2014 at 14:38

4 Answers 4

2

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);
}
answered Oct 10, 2014 at 14:40
Sign up to request clarification or add additional context in comments.

Comments

1

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]);
 }
}
answered Oct 10, 2014 at 14:41

Comments

0

You can simply do this.

var selection = data.map(function(x){
 return x.tags;
}).join().split(",");
answered Oct 10, 2014 at 14:40

Comments

0

i think better use concat array function . see concat function in http://skillgun.com/javascript/arrays/tutorial

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.