Reputation: 1960
[
{'id': 123, 'name': 'apples', 'total': 30},
{'id': 541, 'name': 'oranges', 'total': 42},
{'id': 300, 'name': 'bananas', 'total': 18}
]
How do I output this array in a form like that:
Apples: 30
Oranges: 42
Bananas: 18
I tried
let myArray = [{
'id': 123,
'name': 'apples',
'total': 30
},
{
'id': 541,
'name': 'oranges',
'total': 42
},
{
'id': 300,
'name': 'bananas',
'total': 18
}
]
console.log(JSON.stringify(myArray.map(a => a.name)))
but that's not exactly what I want.
Upvotes: 1
Views: 5545
Reputation: 339
you can also do like this
let data=[
{'id': 123, 'name': 'apples', 'total': 30},
{'id': 541, 'name': 'oranges', 'total': 42},
{'id': 300, 'name': 'bananas', 'total': 18}
]
let update=Object.assign(...data.map(item=> ({[item.name.charAt(0).toUpperCase() + item.name.slice(1)]:item.total})))
console.log(update);
Upvotes: 0
Reputation: 122115
You can use Object.assign
with spread syntax and to create an object from array.
const data = [{'id': 123, 'name': 'apples', 'total': 30},{'id': 541, 'name': 'oranges', 'total': 42},{'id': 300, 'name': 'bananas', 'total': 18}]
const cap = str => str[0].toUpperCase() + str.slice(1)
const result = Object.assign(...data.map(({name, total}) => ({[cap(name)]: total})))
console.log(result)
Upvotes: 1
Reputation: 795
Your array will be something like this:
var fruits = [
{'id': 123, 'name': 'apples', 'total': 30},
{'id': 541, 'name': 'oranges', 'total': 42},
{'id': 300, 'name': 'bananas', 'total': 18}
]
You can loop it for array using for loop.
for(i=0; i<fruits.length; i++)
{
console.log(fruits[i].name + " : " + fruits[i].total);
}
It gives output you desire.
Upvotes: 0
Reputation: 10624
You can do something like this:
var data = [
{'id': 123, 'name': 'apples', 'total': 30},
{'id': 541, 'name': 'oranges', 'total': 42},
{'id': 300, 'name': 'bananas', 'total': 18}
]
console.log(data.map(a => ({[a['name'].charAt(0).toUpperCase() + a['name'].slice(1)]: a['total']})));
Upvotes: 0
Reputation: 979
You'll need to iterate the array
let arr = [{
'id': 123,
'name': 'apples',
'total': 30
},
{
'id': 541,
'name': 'oranges',
'total': 42
},
{
'id': 300,
'name': 'bananas',
'total': 18
}
]
arr.forEach((element) => {
// do stuff with data
let id = element.id;
let name = element.name;
let total = element.total;
console.log(`${name}: ${total}`);
// or write in div/form with innerHtml etc..
});
Upvotes: 0