alex
alex

Reputation: 7611

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. How can I modify the function so it detects the first property that it's an array and loop through it? (e.g. in this case that property is fields).

Upvotes: 0

Views: 69

Answers (4)

Kanad Chourasia
Kanad Chourasia

Reputation: 541

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
}

Upvotes: 3

Mike Tung
Mike Tung

Reputation: 4831

If the goal is to find the first array property you can do the following. Using 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];
})

Upvotes: 0

Mμ.
Mμ.

Reputation: 8552

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
      }
    })
  })
},

Upvotes: 2

A. L
A. L

Reputation: 12679

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()

Upvotes: 1

Related Questions