我有一个对象数组。我正在尝试从数组中筛选出一些对象,并使用以下内容获取新的数组。
[
{
"userId": 1,
"title": "title 1",
"body": "Body for user 1",
"address": {
"country": "Germany",
"state": "State1"
},
"phone": 1234
},
{
"userId": 2,
"title": "title 2",
"body": "Body for user 2",
"address": {
"country": "Canada",
"state": "State2"
},
"phone": 4321
}
]
我如何过滤数组并获得没有address
和phone
的新数组。
任何帮助表示赞赏。谢谢
答案 0 :(得分:3)
您可以使用.map()
和对象分解:
let data = [
{"userId": 1, "title": "title 1", "body": "Body for user 1", "address": {"country": "Germany", "state": "State1"}, "phone": 1234},
{"userId": 2, "title": "title 2", "body": "Body for user 2", "address": { "country": "Canada", "state": "State2"}, "phone": 4321}
];
let result = data.map(({address, phone, ...rest}) => rest);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
文档:
答案 1 :(得分:0)
您可以使用.map
方法来创建新的过滤数组。
map()
方法创建一个新数组,其结果是在调用数组中的每个元素上调用提供的函数
您可以使用destructuring assignment来获取并返回要保留的属性:
data.map(({userId, title, body}) => {
return {userId, title, body}
});
这是一个演示:
const data = [
{
"userId": 1,
"title": "title 1",
"body": "Body for user 1",
"address": {
"country": "Germany",
"state": "State1"
},
"phone": 1234
},
{
"userId": 2,
"title": "title 2",
"body": "Body for user 2",
"address": {
"country": "Canada",
"state": "State2"
},
"phone": 4321
}
];
let res = [];
res = data.map(({userId, title, body}) => {
return {userId, title, body}
});
console.log(res)
答案 2 :(得分:0)
您还可以使用reduce
let res = Object.values(data.reduce((c, {userId,title,body}) => {
c[userId] = c[userId] || {userId, title, body}
return c;
}, {}));