提取内部和对象数组的数组

时间:2017-11-08 21:49:07

标签: javascript

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

我想提取这个[“label1”,“label2”,“label3”,“label4”]

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

但上面的代码打印[[“label1”,“label2”],[“label1”,“label3”],[“label2”,“label4”]]

有人可以帮我这个吗?

3 个答案:

答案 0 :(得分:3)

首先,您可以将objs数组映射为仅获取labels数组,然后使用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);




答案 1 :(得分:0)

使用下划线

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

答案 2 :(得分:0)

您可以使用展开元素和Set

let res = [];

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

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

.filter().includes()

var res = [];

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