如果's的第一个非空数组

Return true if it's first non-empty array

本文关键字:第一个 数组 如果      更新时间:2024-05-05

我有一个对象,它有两种类型的数据:ArrayString:

{
  "livingroom": [
    {
      "app": "",
      "name": "s1",
      "thumbnail": "https://storage.googleapis.com/peterbucket/istagingViewer/sigstaging.com.tw/Cuiti/study/web/thumb_floorplan1.jpg"
    }
  ],
  "study": [
    {
      "app": "",
      "name": "s0",
      "thumbnail": "https://storage.googleapis.com/peterbucket/istagingViewer/sigstaging.com.tw/Cuiti/study/web/thumb_floorplan3.jpg"
    }
  ],
  "outdoor": [],
  "id": "-KF28-_Vdve-u3498eQ1",
  "name": "Cuiti"
}

现在我正在循环所有的值,并且只想返回第一个非空数组(在本例中是livingroom的值)。

// Template
<div v-for="value in object" v-if="isFirstNonEmptyArray(value, object)">
// JavaScript
isFirstNonEmptyArray (value, object) {
  if (value instanceof Array) {
    if (value.length > 0) {
      // What to do here?
    }
  }
},

但正如你所看到的,在检查了值不是空的之后,我被卡住了。我接下来应该写什么?

这是一个棘手的问题,因为Javascript对象的属性上没有排序

换句话说,很难用空值返回第一个这样的属性,因为对象属性的循环不能保证以相同的顺序命中它们。因此,作为一个推论,如果该属性是对象中的第一个此类值,则不可能返回true,因此您的问题无法解决:)

如果您只有一个长度为非空的属性,则可以执行以下操作:

function FirstNonEmptyArray(object) {
    for (var property in object) {
        if (object.hasOwnProperty(property) && (object[property] instanceof Array)) {
            if (object[property].length > 0) {return property;}
       }
}};

如果您有多个具有非空长度的属性,那么不能保证通过对象的迭代顺序。这些属性中的任何一个都可以返回。

如果属性名称的长度为非零,那么最好将其附加到数组中,然后按照您的意愿进行处理:

 function AllNonEmptyArrays(object) {
    var array = []
    for (var property in object) {
        if (object.hasOwnProperty(property) && (object[property] instanceof Array)) {
            if (object[property].length > 0) {array.push(property);}
       }
    return array;
}};

希望这段代码会有用。Js-obejct不保证其密钥的顺序。所以只找出那些数组和非空的密钥

var _localArray = [] // Use to store non empty array 
    for(var keys in a){ // Iterating over object. a is the object
    // Checking if the current key is an array & it's length is >= 1
    if(Object.prototype.toString.call(a[keys] ) === '[object Array]' && a[keys].length>=1) {
      _localArray.push(a[keys]);  // push the key in temp array
    }
    }
    console.log(_localArray[0]); // will log the first non empty array

jsfiddle