0
var objs = [
  {labels: ["label1", "label2"]}, 
  {labels: ["label1", "label3"]},
  {labels: ["label2", "label4"]} 
]

i am trying to extract this ["label1", "label2", "label3", "label4"]

labels = this.get('objs').map(function(obj) {
           return obj.labels.map(function(label) {
             return label;
           });
         });
console.log(labels);

But the above code printed [["label1", "label2"], ["label1", "label3"], ["label2", "label4"]]

Can someone help me with this?

3 Answers 3

3

Firstly you could map your objs array to get just the labels array, then remove dupe entries with Set.

const objs = [
  {labels: ["label1", "label2"]}, 
  {labels: ["label1", "label3"]},
  {labels: ["label2", "label4"]},
];

const r = [...new Set([].concat(...objs.map(({ labels }) => labels)))];

console.log(r);

ES5:

const objs = [
  {labels: ["label1", "label2"]}, 
  {labels: ["label1", "label3"]},
  {labels: ["label2", "label4"]},
];

const r = [...new Set([].concat(...objs.map(function(v) {
  return v.labels;
})))];

console.log(r);

Sign up to request clarification or add additional context in comments.

2 Comments

could you provide this in es5?
@LokeshCherukuri Yeah, sure. I think that destructuring inside argument declaration might caused some compatibility issues.
0

Try this using underscore

labels = _.union(this.get('objs').map(function(obj) {
    return obj.labels.map(function(label) {
        return label;
    })
}))
console.log(labels);

Comments

0

You can use spread element and Set

let res = [];

objs.forEach(({labels}) => res = [...res, ...labels]);

res = [...new Set(res)];

or .filter() and .includes()

var res = [];

objs.forEach(({labels}) => 
  res = [...res, ...labels.filter(prop => !res.includes(prop))]);

Comments

Your Answer

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.