如何过滤包含键和值的数组

时间:2019-12-31 06:49:14

标签: javascript

我有一个JavaScript对象数组

[
   {path: "/login", meta: {nav :true},
   {path: "/welcome"}
   {path: "/logout", meta: {nav :true},
   {path: "/home"}
]

我需要类似的输出

[
   {path: "/login", meta: {nav :true},
   {path: "/logout", meta: {nav :true},
]

你能帮我吗? 谢谢

正在测试

let data = [
  {path: "/login", meta: {nav :true}, { path: "/welcome" } ,
  {path: "/logout", meta: {nav :true},
  {path: "/home"},
]
data.filter(function(route) {
    return route.meta;
});

2 个答案:

答案 0 :(得分:1)

您可以使用Array.filter()

var arr = [
   {path: "/login", meta: {nav :true}},
   {path: "/welcome"},
   {path: "/logout", meta: {nav :true}},
   {path: "/home"}
];
 var res = arr.filter(({meta}) => meta);
 
 console.log(res);

您的代码存在的问题是您没有为过滤后的结果分配左手代码:

let data = [
  {path: "/login", meta: {nav :true}}, 
  { path: "/welcome"} ,
  {path: "/logout", meta: {nav :true}},
  {path: "/home"}
]
var res = data.filter(function(route) {
    return route.meta;
});

console.log(res);

答案 1 :(得分:0)

您可以使用Array.filter

let arr = [
   {path: "/login", meta: {nav :true}},
   {path: "/welcome", meta: null},
   {path: "/logout", meta: {nav :true}},
   {path: "/home"}
];
let res = arr.filter(({meta}) => meta && meta.nav === true);
 
console.log(res);

豫ICP备18024241号-1