如果值为空,则删除对象

时间:2018-12-01 18:57:34

标签: javascript

array1是对象的数组,所以像这样:

pi.read(26)

array2也是对象数组,所以像这样:

pi.wave_send_using_mode(wid2, pigpio.WAVE_MODE_REPEAT_SYNC)

我想获取基于array1的特定ID的照片值。我的array2可以具有重复的id值,所以我想忽略带有空字符串的那个。

所以在一天结束时,我想返回类似的内容
0: {Group: 1, names: "Lastname1, Firstname1", id: 20000001} 1: {Group: 2, names: "Lastname2, Firstname2", id: 20000002} 2: {Group: 3, names: "Lastname3, Firstname3", id: 20000003}

5 个答案:

答案 0 :(得分:1)

您可以使用find()来获取所需的值。它将返回找到的第一个值。空字符串在javascript中是错误的,因此您可以像下面这样编写find回调:

let arr = [
  {id: "20000001", photo: ""},
  {id: "20000001", photo: "/9j/4AAQSkZJRgABAQAAAQABAAD/4QB6RXhpZgAASUkqAAgAAA…9a1EtFKAnd09f/rVlwfdFbVw7LPIoOAGNYwjc/SIaxR//2Q=="},
  {id: "20000002", photo: ""},
  {id: "20000003", photo: ""},
  {id: "20000004", photo: ""}
]

let found = arr.find(item => item.photo && item.id === '20000001')
console.log(found.photo)

答案 1 :(得分:1)

let arr = [{
    id: "20000001",
    photo: ""
  },
  {
    id: "20000001",
    photo: "/9j/4AAQSkZJRgABAQAAAQABAAD/4QB6RXhpZgAASUkqAAgAAA…9a1EtFKAnd09f/rVlwfdFbVw7LPIoOAGNYwjc/SIaxR//2Q=="
  },
  {
    id: "20000002",
    photo: ""
  },
  {
    id: "20000003",
    photo: ""
  },
  {
    id: "20000004",
    photo: ""
  }
]

function findItemByID(arr, id) {
  return arr.find((photoObj) => {
    return photoObj.photo.trim().length !== 0 && photoObj.id === id
  })
}

let photoObj = findItemByID(arr, "20000001");
console.log(photoObj.photo);

答案 2 :(得分:0)

var array2 = [{id: "20000001", photo: ""},
{id: "20000001", photo: "/9j/4AAQSkZJRgABAQAAAQABAAD/4QB6RXhpZgAASUkqAAgAAA…9a1EtFKAnd09f/rVlwfdFbVw7LPIoOAGNYwjc/SIaxR//2Q=="},
{id: "20000002", photo: ""},
{id: "20000003", photo: ""},
{id: "20000004", photo: ""}];

var result = array2.filter(function(a){ return a.photo }).map(a => a.photo);

答案 3 :(得分:0)

尝试这样的事情:

function getForId(photos, id) {
    var tmp = photos.filter(ph => ph.id == id).filter(ph => ph.photo != "");
    if (tmp.length == 0) return undefined;
    return tmp[0];
}

...

x = getForId(array2, "20000001");

答案 4 :(得分:0)

您可以映射(通过Array.map)主数组,并为每个项目使用Array.find获取其photo。然后像这样分配给当前项目:

const data = [{ Group: 1, names: "Lastname1, Firstname1", id: 20000001 }, { Group: 2, names: "Lastname2, Firstname2", id: 20000002 }, { Group: 3, names: "Lastname3, Firstname3", id: 20000003 } ]
const images = [ {id: "20000001", photo: ""}, {id: "20000001", photo: "/9j/4AAQSkZJRgABAQAAAQABAAD/4QB6RXhpZgAASUkqAAgAAA…9a1EtFKAnd09f/rVlwfdFbVw7LPIoOAGNYwjc/SIaxR//2Q=="}, {id: "20000002", photo: ""} ]

const result = data.map(x => {
  let img = images.find(i => x.id == i.id && i.photo != '')	
  if(img) Object.assign(x, {photo: img.photo})
  return x
})
console.log(result)