aha
aha

Reputation: 21

javascript How to get an objects value from an array full of objects?

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

Answers (4)

Jonas Wilms
Jonas Wilms

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

Patrick Roberts
Patrick Roberts

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

user736893
user736893

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

Ulysse BN
Ulysse BN

Reputation: 11423

You can iterate through an array in javascript, for instance with a for...of loop:

for (const item of myArray) {
    /* do stuff with `item` */
    console.log(item.name + ' costs ' + item.price)
}

Upvotes: 2

Related Questions