Home > Blockchain >  How to search inside a object using a index and search through the values of a array inside a object
How to search inside a object using a index and search through the values of a array inside a object

Time:12-11

I have recently found a code that lets you get you the value of a array inside a object using a index number but i would like to search through that array of numbers how can i solve this problem?

this is the code that i have found using a index to get the array, i have tried using another function from a stackoverflow user but nothing seems to work.



let testObj = {
    tableA : [0,0,0,0,1,1,1,1],
    tableB : [0,0,1,1,0,0,1,1],
    tableC : [0,1,0,1,0,1,0,1],
    key : function(n){
        return this[Object.keys(this)[n]]
    }
}


    console.log(testObj.key(1));// [0,0,0,0,1,1,1,1]

But i cant search through the tableA values with a for loop or for example i want to get the second number of that array like this



let testObj = {
    tableA : [0,0,0,0,1,1,1,1],
    tableB : [0,0,1,1,0,0,1,1],
    tableC : [0,1,0,1,0,1,0,1],
    key : function(n){
        return this[Object.keys(this)[n]]
    }
}


    console.log(testObj.key(1,0)); // 0

this code above is what i want to happen too use another index to get the value of that array

CodePudding user response:

let testObj = {
    tableA : [0,0,0,0,1,1,1,1],
    tableB : [0,0,1,1,0,0,1,1],
    tableC : [0,1,0,1,0,1,0,1],
    key : function(n){
        return this[Object.keys(this)[n]]
    },
    nestedKey: function(n, x){
        return this[Object.keys(this)[n]][x]
    }
}

Is this what you wanted?

Update:

You can use your already defined key function aswell:

nestedKey: function(n, x){
        return this.key(n)[x]
}
  • Related