例如这是我拥有的数组的数组
arr: [
[
{
type: "some type",
name: "some name"
},
{
type: "some type",
name: "some name"
}
],
[
{
type: "some type",
name: "some name"
},
{
type: "some type",
name: "some name",
customAttr: "something custom"
}
],
[
{
type: "some type",
name: "some name"
},
{
type: "some type",
name: "some name"
},
customAttr: "something custom"
]];
只要在这个数组的数组下找到 customAttr
,我就想删除或更改。它可以在 Array 层、Objects 层甚至更深的层中找到。另外,我不想从索引 0 开始,而是在它之后。
我试过了
arr.forEach(e => e).filter(s => s.customAttr)
但它只到达一层,我想改变数组
是否有一个函数,即使在 Lodash 中也可以用于此目的?
谢谢。
最佳答案
如果您有资格使用平面阵列,那么也许它适合您:
const arr = [
[
{
type: "some type1",
name: "some name"
},
{
type: "some type2",
name: "some name"
}
],
[
{
type: "some type3",
name: "some name"
},
{
type: "some type4",
name: "some name",
customAttr: "something custom"
}
],
[
{
type: "some type5",
name: "some name"
},
{
type: "some type6",
name: "some name"
},
customAttr= "something custom1"
]
];
const flatArray = (arr) => {
return arr.reduce(function (flat, toFlatten) {
return flat.concat(Array.isArray(toFlatten) ? flatArray(toFlatten) : toFlatten);
}, []);
}
const flattened = flatArray(arr);
const result = flattened.filter(fi => fi.type && fi.name ).map(f=> {
return {
type: f.type,
name: f.name
}
});
console.log(result);
更新:
为了避免扁平化数组,您可以执行以下操作(注意它只适用于二维数组):
const testArray = [
[
{
type: "some type1",
name: "some name"
},
{
type: "some type2",
name: "some name"
}
],
[
{
type: "some type3",
name: "some name"
},
{
type: "some type4",
name: "some name",
customAttr: "something custom"
}
],
[
{
type: "some type5",
name: "some name"
},
{
type: "some type6",
name: "some name"
},
customAttr= "something custom1"
]
];
const beautifyArray = (srcArray) => {
srcArray.forEach((el, i) => {
el = el.filter(fi=> fi.type && fi.name)
.map(a => { return { type: a.type, name: a.name}});
testArray[i] = el;
});
console.log(testArray);
}
beautifyArray(testArray)
关于javascript - 当在 Array of Arrays 中找到时,您将如何搜索属性名称并更改(删除)它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58731818/