简体   繁体   中英

extract array that is inside and array of objects

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?

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); 

Try this using underscore

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

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))]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM