Reputation: 21
I'm kinda new to javascript and came across the following situation: There are some products which have to get in a list and calculated. I thought about making this list an global array to be available across the whole site. The products themselves will be objects with attributes like name, type, price.
The problem now is that I have an array like this:
[{name: name, type: type, price: price}{name: name, type: type, price: price}...]
The user will be able to add as much of these objects as he likes. And now I can't find out how to be able to list for example all selected names. I saw how people printed out the complete array and an object specific attribute but I'm not able to combine them.
I'm a trainee at work and for the next week there is nobody who can help me and because the code is from work I'm not allowed to share a single line of it. Thanks for helping! ^^"
Upvotes: 0
Views: 789
Reputation: 138537
You could get all the names through mapping the objects to their names
array.map(obj => obj.name)
To display it, you can build up one long string, where every of these names is seperated by a newline (\n):
.join("\n");
Upvotes: 0
Reputation: 51957
@UlysseBN's answer is fine if you're using the ECMAScript 6 standard, but if not, here's a canonical ECMAScript 5 approach using Array#forEach()
:
myArray.forEach(function (item, index, myArray) {
console.log(item.name + ' costs ' + item.price)
})
Upvotes: 1
Reputation:
It's not 100% clear what you are asking, but see if this helps:
var data = [
{name: "apple", type: "fruit", price: 5},
{name: "banana", type: "fruit", price: 4}
];
console.log("The first object in the array is an " + data[0].name);
Upvotes: 0