0

I am getting a set of data using getJSON like this:

var url = 'http://localhost:5000/api/items';
$.getJSON(url, function(response) {
  var response2 = []
  console.log(response)
});

My console output is the following:

[{"id": 1, "price": 20, "name": "test"}, {"id": 4, "price": 30, "name": "test2"}]

I need to convert these values into an array in this format:

[[1, 20, "test"], [4, 30, "test2"]]

I tried the following code but the result is different:

$.each(response, function (key, val) {
  response2.push(val)
});

console.log(response2)  // output = [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

Any help is really appreciated!

2 Answers 2

2

To do what you require you can use Object.values to get the values of all the properties from an object as an array. From there you can use map() to build a new array containing them all:

// AJAX response:
let response = [{"id": 1, "price": 20, "name": "test"}, {"id": 4, "price": 30, "name": "test2"}];

let  response2 = response.map(Object.values);
console.log(response2);

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

Comments

1

If you need to do it using array here is another way .

Demo Code :

var response = [{
  "id": 1,
  "price": 20,
  "name": "test"
}, {
  "id": 4,
  "price": 30,
  "name": "test2"
}]
var outerarray = [];
$.each(response, function(key, val) {
  innerarray = []
  innerarray.push(val.id, val.price, val.name) //push value
  outerarray.push(innerarray)
});
console.log(outerarray)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

1 Comment

Thank you very much, and sorry for the "noob" question :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.