我在这样的快速后端中得到了一个JSON对象数组,每个对象都包含一个数组,其键名为projectTags
:
[ { projectTags: [ 'rer' ] },
{ projectTags: [ 'a10' ] },
{ projectTags: [ 'a10', 'c12', 'e14' ] },
{ projectTags: [ 'a10', 'e14', 'b11', 'c12', 'd13' ] } ]
我想将这些数组合并在一起,结果也将没有相同的标签。因此理想情况下,它看起来应该像这样:
[ { projectTags: [ 'rer', 'a10', 'c12', 'e14', 'b11', 'd13' ] },]
那我该怎么做呢?
答案 0 :(得分:4)
使用concat
可以创建一个数组,使用Set可以获取唯一值:
const data = [ { projectTags: [ 'rer' ] },{ projectTags: [ 'a10' ] }, { projectTags: [ 'a10', 'c12', 'e14' ] }, { projectTags: [ 'a10', 'e14', 'b11', 'c12', 'd13' ] } ];
const result = [{ projectTags: [...new Set([].concat(...data.map(o => o.projectTags)))]}];
console.log(result);
答案 1 :(得分:2)
您可以将地图OnPropertyChanged()
{归入一个尚未添加的元素reduce
。
concat
答案 2 :(得分:1)
您可以使用Set
并添加所有标签。
var data = [{ projectTags: ['rer'] }, { projectTags: ['a10'] }, { projectTags: ['a10', 'c12', 'e14'] }, { projectTags: ['a10', 'e14', 'b11', 'c12', 'd13'] }],
result = [{ projectTags: Array.from(
data.reduce(
(s, { projectTags }) => (
projectTags.forEach(Set.prototype.add, s),
s
),
new Set
)
) }];
console.log(result) ;
答案 3 :(得分:0)
如果您不需要重复:
var arr = [ { projectTags: ['rer'] },
{ projectTags: ['a10'] },
{ projectTags: ['a10', 'c12', 'e14'] },
{ projectTags: ['a10', 'e14', 'b11', 'c12', 'd13'] }];
var arr2 = [];
arr.forEach(function (e) {
var i = e.projectTags;
for (var x = 0; x < i.length; x++) {
if (arr2.indexOf(i[x]) == -1) arr2.push(i[x]);
}
});
console.log(arr2);
答案 4 :(得分:0)
这是我用JavaScript编写的代码。 希望对您有帮助。
//问题中提供的数据列表。
var dataList = [
{ projectTags: [ 'rer' ] },
{ projectTags: [ 'a10' ] },
{ projectTags: [ 'a10', 'c12', 'e14' ] },
{ projectTags: [ 'a10', 'e14', 'b11', 'c12', 'd13' ] }
];
//Final Result
var dataListAfterMerge = [];
//the list of unique items to be added.
var items = [];
//to verify if the item is already present in the new list (i.e. items).
var isAdded = false;
//Call this function on button click or any place you needed.
merge = function() {
for (var data of dataList){
for(var item of data.projectTags) {
for(var newItem of items) {
if(item == newItem) {
isAdded = true;
break;
}
}
if(!isAdded) {
items.push(item);
}
isAdded = false;
}
}
dataListAfterMerge.push({projectTags: items});
console.log(dataListAfterMerge);
}
答案 5 :(得分:0)
您可以使用reduce创建一个将所有元素放在一起的数组,然后使用Set删除所有重复项:
const arr = [ { projectTags: ['rer'] },
{ projectTags: ['a10'] },
{ projectTags: ['a10', 'c12', 'e14'] },
{ projectTags: ['a10', 'e14', 'b11', 'c12', 'd13'] }];
const withoutDuplicates = [... new Set(arr.reduce((newArray, element) => {
newArray.push(...element.projectTags);
return newArray;
}, []))];