Convert array of Objects to 2d array

Viewed 1095

How can I convert this Array of Objects

var tags= [
  {id: 0, name: "tag1", project: "p1", bu: "test"},
  {id: 1, name: "tag2", project: "p1", bu: "test"},
  {id: 2, name: "tag3", project: "p3", bu: "test"}
];

Into this 2d array:

[["tag1","p1", "test"],
["tag2","p1", "test"],
["tag3","p3", "test"]]
3 Answers

You could use map

var tags= [ {id: 0, name: "tag1", project: "p1", bu: "test"}, {id: 1, name: "tag2", project: "p1", bu: "test"}, {id: 2, name: "tag3", project: "p3", bu: "test"} ];
var res=tags.map(o=>[o.name,o.project,o.bu])
console.log(res)

Or You could use a more generic approach

var tags= [ {id: 0, name: "tag1", project: "p1", bu: "test"}, {id: 1, name: "tag2", project: "p1", bu: "test"}, {id: 2, name: "tag3", project: "p3", bu: "test"} ];
var res = tags.map(({id,...rest}) => Object.values(rest))
console.log(res)

If you want to conserve all properties you can use

let twoDArray = tags.map(tag => Object.values(tag))

// [[0, "tag1", "p1", "test"], [1, "tag2", "p1", "test"], [2, "tag3", "p3", "test"]]

Array.map will help you.

https://www.geeksforgeeks.org/javascript-array-map-method/

var tags= [
  {id: 0, name: "tag1", project: "p1", bu: "test"},
  {id: 1, name: "tag2", project: "p1", bu: "test"},
  {id: 2, name: "tag3", project: "p3", bu: "test"}
];
          
   var newArr = tags.map(function(val, index){ 
            return [val.name,val.project,val.bu]
   }) 
          
   console.log(newArr) 

Related