Home > Software engineering >  Javascript array of multiple object
Javascript array of multiple object

Time:03-29

How to convert the 1 object with multiple item inside to an array of object? please see the picture below to understand what i meant, thanks

    var author = (`SELECT author, title, remarks, status, date FROM Transaction`, 1000, data=>{
      let obj = {[author: [], book: [], condition: [], status: [], date: []]}
        for(let x = 0; x < data.length; x  ){
          obj.author.push(data[x][0]);
          obj.book.push(data[x][1]);
          obj.condition.push(data[x][2]);
          obj.status.push(data[x][3]);
          obj.date.push(data[x][4]);
        }
      console.log("obj: ", obj)
        return resolve(obj);
    })

The Current result of console.log("obj: ", obj)

{
    "authors": "testuser,testname",
    "books": "440936785,440936694",
    "conditions": "Very Good,New,",
    "status": "Not Available,Available",
    "datepublished": "Mon Mar 28 2022 18:42:24 GMT 0800 (Philippine Standard Time),Mon Mar 28 2022 18:42:39 GMT 0800 (Philippine Standard Time)"
}

What I want result:

{
    "authors": "testname",
    "books": "440936694",
    "conditions": "New",
    "status": "Available",
    "datepublished": "Mon Mar 28 2022 18:42:24 GMT 0800 (Philippine Standard Time)"
},
{
    "authors": "testname",
    "books": "440936694",
    "conditions": "New,",
    "status": "Available",
    "datepublished": "Mon Mar 28 2022 18:42:39 GMT 0800 (Philippine Standard Time)"
}

CodePudding user response:

You have a list of rows and want to create a list of objects. That means you have to convert every row to an object. Such a transformation is typically done with Array#map, which applies a function to every element in an array a produces a new array from the return value of that function:

const objects = data.map(row => ({
  author: row[0],
  book: row[1],
  condition: row[2],
  status: row[3],
  date: row[4],
}));

The library you are using to query the database might also be able to already create an object per row (using the column names) so you don't have to do the mapping yourself.

  • Related