删除javascript中的数组



每个不需要的id键都有一个数组。这是一种小组休息

const header = [
[
{ id: "1",
text: "A",
},
],
[
{ id: "2",
text: "B",
array:[1,2,3],
},
{ id: "2",
text: "B1",
},
],
[
{ id: "3",
text: "A",
},
],
];

结果应该如下所示。相同id之间的数组应该消失。只保留一个包含数据的数组。

const header = [
{ id: "1",
text: "A",
},
{ id: "2",
text: "B",
array:[1,2,3],
},
{ id: "2",
text: "B1",
},
{ id: "3",
text: "A",
},
];

要归档的内容称为flatten。
JavaScript有一个内置的方法来归档这个:Array.prototype.flat().
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat

示例(取自上面的源代码)

const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());
// expected output: [0, 1, 2, 3, 4]
const arr2 = [0, 1, 2, [[[3, 4]]]];
console.log(arr2.flat(2));
// expected output: [0, 1, 2, [3, 4]]

你可能必须使用嵌套循环,因为数组的每个索引也是一个数组,并将项压入一个新数组。

const header = [
[{ id: '1', text: 'A' }],
[
{ id: '2', text: 'B', array: [1, 2, 3] },
{ id: '2', text: 'B1' },
],
[{ id: '3', text: 'A' }],
];
const newHeader = [];
header.forEach(headerItems => {
headerItems.forEach(headerItem => {
newHeader.push(headerItem)
});
})
console.log(newHeader);

可以使用flat()方法。

此链接与平面方法相关:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat

这是我的代码:

// before
const header = [
[{ id: '1', text: 'A' }],
[
{ id: '2', text: 'B', array: [1, 2, 3] },
{ id: '2', text: 'B1' }
],
[{ id: '3', text: 'A' }]
]
// expected output
const headerFlat = [
{ id: '1', text: 'A' },
{ id: '2', text: 'B', array: [1, 2, 3] },
{ id: '2', text: 'B1' },
{ id: '3', text: 'A' }
]
// using flat()
const flat = header.flat()
console.log(flat)

最新更新