Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert array of Objects to 2d array

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"]]
like image 843
Omi in a hellcat Avatar asked Apr 25 '26 13:04

Omi in a hellcat


2 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)
like image 134
Sven.hig Avatar answered Apr 27 '26 02:04

Sven.hig


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"]]
like image 34
khrzstoper Avatar answered Apr 27 '26 03:04

khrzstoper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!