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?
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);
You can use the function map
.
let result = arr.map(({name}) => name);
The array result
will have the name of the brands.
Example
let arr = [{"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 result = arr.map(({name}) => name); console.log(result);
.as-console-wrapper { min-height: 100%; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.