我有一个类似的数组
let array = [
{
name: "1-name",
age: 18,
direction: "jsjs"
phone: 7182718
},
{
name: "2-name",
age: 38,
direction: "jsjsjs"
},
{
name: "3-name",
age: 58,
direction: "jsjsjsjs"
}
]
我想根据它的键对它进行过滤得到一个像这样的数组
[
{
name: "1-name",
direction: "jsjs"
},
{
name: "2-name",
direction: "jsjsjs"
},
{
name: "3-name",
direction: "jsjsjsjs"
}
]
你能帮帮我吗?我试着解决这个问题,但没有成功
您可以使用数组map
函数
请看下面的例子:
const arr = [
{
name: "1-name",
age: 18,
direction: "jsjs",
phone: 7182718
},
{
name: "2-name",
age: 38,
direction: "jsjsjs",
phone: 7182718
},
{
name: "3-name",
age: 58,
direction: "jsjsjsjs",
phone: 7182718
}
]
const result = arr.map(({ name, direction }) => {
return {
name,
direction
};
})
console.log(result);
你可以试试这个代码:
let newArr = [];
array.forEach((e) => {
newArr.push({ name: e.name, direction: e.direction });
});
map
方法将工作。如何实现这取决于你是否想创建一个新的数组result
与以前的对象删除,或简单地返回那些你想要保持。这将创建一个新的数组您的原始数组将不受影响。
array.map(function (result) {
delete result.age;
delete result.phone;
});
console.log(result)