Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a JavaScript Method/ Function to loop Objects via Keys into a array?

Hy , this is my API

 // --- API
        // Replace ./data.json with your JSON feed
        fetch('http://127.0.0.1:8000/cars/')
            .then(response => {
                return response.json()
            })
            .then(data => {
                // Work with JSON data here
                //-- go to array named "results"
                obj1 = data.results 
                console.dir(obj1) 

<...>

this is my API Output. Some Array with Objects and Random Data.

[{"id":3,"name":"Audi","price":11},{"id":2,"name":"Mercedes","price":22},{"id":1,"name":"BMW","price":99},{"id":4,"name":"Trabant","price":113}]

I would like to loop the Objects by their key into different arrays in JavaScript. So that Chart.js can handle it as labels, for instance.

Example

["Audi", "Mercedes", "BMW", "Trabant"]

So i tried these three different Methods to do the job

Object.keys
Object.values
Object.entries

An i also tried a loop

                // --- LOOP
                var arr = obj1
                for (var i = 0; i < arr.length; i++) {
                    console.dir(arr[i]);
                }
                console.dir(arr)

But i only get rid of the [ ] with the loop and in the end its a too messy. So i ask myself is there something like

{% for some_value in Object.name %}
{{ some_value ]}
{% endfor %}

like in Django? A simple Loop through Objects by their key?

like image 476
black_hole_sun Avatar asked Jan 26 '23 09:01

black_hole_sun


1 Answers

Try (we use standard map and arrow function)

let d = [{"id":3,"name":"Audi","price":11},{"id":2,"name":"Mercedes","price":22},{"id":1,"name":"BMW","price":99},{"id":4,"name":"Trabant","price":113}];

let r= d.map(x=>x.name);

console.log(r);
like image 71
Kamil Kiełczewski Avatar answered Jan 29 '23 12:01

Kamil Kiełczewski