0

I am really new to this and I just got a grasp of json data and I want it as a regular array

loginAndDetails.get(`SELECT * FROM logTB` , (err,data) => {
   console.log(data)
})

//output might be 1d or 2d
  {
    entry1: 'data1',
    entry2: 'data2',
    .,    
    .,
    entryN: 'dataN'
  }


loginAndDetails.all(`SELECT * FROM logTB` , (err,data) => {
   console.log(data)
})
// alternative output:
  [{
    entry1: 'data1',
    entry2: 'data2',
    .,    
    .,
    entryN: 'dataN'
  },
{
    entry1: 'data1',
    entry2: 'data2',
    .,   
    .,
    entryN: 'dataN'
  }]

but I have already created all my function to work with a normal JS array like this

['data1','data2',...,'dataN'] 

(or) 

[['data1','data2',...,'dataN'],
['data1','data2',...,'dataN']]

so is there a way to convert all the data dynamically because Some times it might be a 2d array some times it might be a 1d array and there might be 'n' number of objects

do I have to create a function to build this or is there any other method

2 Answers 2

1

You can do something like this, it will give you an array of arrays.

var finalResult = [];

// checking if data is an array of objects
if (Array.isArray(data)){
    for (var i=0; i < data.length; i++ ){
        console.log(data[i]);
        var result = getFlatArray(data[i]);
        finalResult.push(result);
    }
    console.log(finalResult);
}
else{
    finalResult = getFlatArray(data);
    console.log(finalResult);
}

function getFlatArray(data){
    var result = [];
    for(var j in data){
        result.push([data[j]]);
    }
   return result;
}

But if you want to access your JSON objects you can do as follows.]

For 1d:- data.entry1

For 2d:- data is just a javascript array so you can traverse it with a normal loop and access the objects inside the loop with the array index.

for(var i=0; i < data.length; i++){
    // access the data in the loop using array index
    data[i].entry1;
}
Sign up to request clarification or add additional context in comments.

Comments

0

The bulk of the heavy lifting here can be done with Object.values() We can then use a function to treat the 1d and 2d result sets appropriately

const output1d = {col1: 'col1', col2: 'col2', col3: 'col3'};
const output2d = [{r1col1: 'col1', r1col2: 'col2'}, {r2col1: 'col1', r2col2: 'col2'}];

function resultsToArray(resObj) {
  if (Array.isArray(resObj)) {
    return resObj.map((item) => Object.values(item));
  } else {
    return Object.values(resObj);
  }
};

console.log(resultsToArray(output1d));

console.log(resultsToArray(output2d));

Output...

[ 'col1', 'col2', 'col3' ]
[ [ 'col1', 'col2' ], [ 'col1', 'col2' ] ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.