skip to Main Content

I want to convert this:

data= [{id: 1, name: 'james', country: 'US'}, {id: 2, name: 'john', country: 'NG'}]

to this:

newdata =[[1,'james', 'US'], [2,'john', 'NG']] 

I tried pushing the data to a new array but couldn’t give me my desired result:

const newdata = [];

for (let index = 0; index < data.length; index++) {
  newdata.push(data[index].name);
}

but it’s giving me just the names. I understand that this line data[index].name is the cause.

2

Answers


  1. You can use this function:
    function transformData(data) { return data.map(item => [item.id, item.name, item.country]); }

    Login or Signup to reply.
  2. You can use Object.values to turn an object to an array with only their values:

    data = [{id: 1, name: 'james', country: 'US'}, {id: 2, name: 'john', country: 'NG'}]
    
    convertedData = data.map(d => Object.values(d))
    console.log(convertedData)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search