3

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"]]
1

3 Answers 3

6

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)

Sign up to request clarification or add additional context in comments.

2 Comments

I am getting an error: tags.map is not a function. This Array of Objects is retrieved from an API call and comes in the exact format I posted in the question above. If its not an array of objects is it just and object?
@Omiinahellcat yes in that case it's more than likely it's an object and not an object of type array
2

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"]]

3 Comments

... or even tags.map(Object.values). But in either case, you'd have to ensure that all objects had their properties in the same order.
add running snippet. @khrzstoper
.map(({id,...rest}) => Object.values(rest)) would be a bit closer to what OP has requested
2

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) 

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.