简体   繁体   English

如何找到对象中数组的第一个属性?

[英]How to find the first property that is an array in an object?

I'm creating a function that loops through an array like this: 我正在创建一个遍历这样的数组的函数:

schema: [{
  name: 'firstRow',
  fields: [{
    name: 'name',
    text: 'Name',
    type: 'text',
    col: 12,
    value: ''
  }]
}, {

And returns a callback with the values of the objects: 并返回带有对象值的回调:

eachDeep (array, callback) {
  array.forEach(item => {
    item.fields.forEach(field => {
      callback(field)
    })
  })
},

As you can see the item.fields.forEach part is harcoded. 如您所见, item.fields.forEach部分已编码。 How can I modify the function so it detects the first property that it's an array and loop through it? 我如何修改该函数,以便它检测到它是数组的第一个属性并遍历它? (eg in this case that property is fields ). (例如,在这种情况下,属性是fields )。

You can check if the field is not an array or not, if so loop it, otherwise do something else with it. 您可以检查该字段是否不是数组,如果是,请对其进行循环,否则请对其进行其他操作。

 var data = [{ name: 'firstRow', fields: [{ name: 'name', text: 'Name', type: 'text', col: 12, value: '' }] }, { name: 'firstRow', fields: [{ name: 'name', text: 'Name', type: 'text', col: 12, value: '' }] }]; eachDeep (array, callback) { array.forEach(item => { // loop through each property again item.forEach(prop => { // if property is an array if (prop instanceof Array) { prop.forEach(field => callback(field)); } else { // property is not an array // do something else } }) }) }, 

To find whether a property of an object is an array or not you can also use this one: 要查找对象的属性是否为数组,还可以使用以下方法:

//let item be your object's property
if(typeof item == "object" && item.length > 0){
    //do whatever if it is an array
}

 var big_array = [ { name: 'firstRow', fields: [{ name: 'name', text: 'Name', type: 'text', col: 12, value: '' }] } ]; for (let item of big_array) { for (let key in item) { if (Array.isArray(item[key]) ) { console.log('this is an array do something:', key); } } } 

You could check using Array.isArray() 您可以使用Array.isArray()检查

If the goal is to find the first array property you can do the following. 如果目标是找到第一个数组属性,则可以执行以下操作。 Using ES6. 使用ES6。

const schema = [{
               name: 'firstRow',
               fields: [{
                         name: 'name',
                         text: 'Name',
                         type: 'text',
                         col: 12,
                         value: ''
                      }]
               }]

let firstArr;
schema.forEach(item => {
  firstArr = Object.keys(item).filter(k => Array.isArray(item[k]))[0];
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM