简体   繁体   English

javascript如何从充满对象的数组中获取对象值?

[英]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. 我是javascript的新手,遇到了以下情况:有些产品必须列入清单并进行计算。 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! 感谢您的帮助! ^^" ^^“

You can iterate through an array in javascript, for instance with a for...of loop: 您可以遍历javascript中的数组,例如使用for...of循环:

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

@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() : 如果您使用的是ECMAScript 6标准,则@UlysseBN的答案很好,但是如果没有,这是使用Array#forEach()的规范ECMAScript 5方法:

myArray.forEach(function (item, index, myArray) {
  console.log(item.name + ' costs ' + item.price)
})

It's not 100% clear what you are asking, but see if this helps: 并不是100%清楚您的要求,但是请问这是否有帮助:

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

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): 要显示它,您可以构建一个长字符串,其中每个名称用换行符(\\ n)分隔:

.join("\n");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM