通过对象的内部数组进行映射

时间:2018-10-03 18:07:13

标签: javascript

我有这个对象:

let arr = [{  
    id : 1,
    usr : 'pimba',
    xyz: null
  },
  {
    id  : 2,
    usr : 'aloha',
    xyz: {
     xyz_id: 2      
    }    
  },
  {
    id  : 3,
    age : 'pruu',
    xyz: null
  }];

您会注意到,有时xyz为null,有时不是。
我需要识别它是否为null,以便可以阅读。
我试图使用map()函数,但是不能将某种过滤器设置为仅在不为null的情况下执行匿名函数。

我设法做到了这样:

let result = Object.values(arr).map(function(row){
  if(row['xyz'] != null) {
    console.log(row['xyz_id']);
  }
});

如果我想要一个仅包含xyz_id的新数组怎么办?有更短的版本吗?

第二种情况:

xyz中有多个值,并且没有“命名”。

let arr = [{  
    id : 1,
    usr : 'pimba',
    xyz: null
  },
  {
    id  : 2,
    usr : 'aloha',
    xyz: {
     xyz_id: {"value1Here", "Value2Here"}      
    }    
  },
  {
    id  : 3,
    age : 'pruu',
    xyz: null
  }];

3 个答案:

答案 0 :(得分:3)

似乎您只想为具有非空SELECT to_timestamp(posts.createat/1000), posts.message, users.username, channels.displayname, channels.name, channels.type FROM posts INNER JOIN users ON posts.userid = users.id INNER JOIN channels ON posts.channelid = channels.id WHERE posts.message ILIKE ANY (VALUES ('%testValue1%'),('%testValue2%'),('%testValue3%'),('%testValue4%')) 属性的元素映射数组。一种选择是同时使用xyz.filter方法。另一种选择是使用.map方法:

.reduce

答案 1 :(得分:2)

您可能想看看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

const notNull = arr.filter(elm => elm.xyz !== null);

答案 2 :(得分:1)

var a = {one: 1, two: null, three: 3, four: true}
var y = []
let scan = (obj) => { 
  Object.keys(obj).forEach(x => {
    if (obj[x] === null) {
       console.log('Its null')
    } else { 
       // Extend here to datatypes
      y.push(obj[x])
    }
  });
}
scan(a)
console.log(y)

相关问题