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”]]
有人可以帮我这个吗?
答案 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))]);