0

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! ^^"

Anthony Pham
3,1065 gold badges32 silver badges38 bronze badges
asked Aug 2, 2017 at 14:55
2
  • 2
    Welcome to SO - what have you tried? You are expected to at least show some effort and ask for help if you run into issues, this is not a code writing service Commented Aug 2, 2017 at 14:58
  • I'm sorry @DarrenSweeney, I'm completely new here, never asked anything on a forum.. ^^" I will keep this in mind for my future questions. Commented Aug 3, 2017 at 6:58

4 Answers 4

2

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)
}
answered Aug 2, 2017 at 15:00

Comments

1

@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)
})
answered Aug 2, 2017 at 15:04

2 Comments

Thank you, exactly what I needed!! :)
0

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);

answered Aug 2, 2017 at 15:02

Comments

0

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");
answered Aug 2, 2017 at 15:20

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.