javascript 使用一个属性连接对象数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18430357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
join array of objects by using one property
提问by Steven De Groote
I've got an array of objects with a few properties, such as 'value' and 'label'.
我有一组具有一些属性的对象,例如“值”和“标签”。
array.join(' ')
of course gives me "[object] [object]", but instead I need to get a string of the 'value' properties of all objects, separated by a space.
array.join(' ')
当然给了我“[object] [object]”,但是我需要获取所有对象的“value”属性的字符串,用空格分隔。
What is the shortest way to do this, and is this possible without writing a for loop?
执行此操作的最短方法是什么,这是否可能不编写 for 循环?
回答by Arun P Johny
Try using jQuery.map()- Array.map()not used because of IE < 9 support
尝试使用jQuery.map()-由于 IE < 9 支持,未使用Array.map()
For JSON.stringify()- use json2for old browser support
对于JSON.stringify()- 使用json2来支持旧浏览器
$.map(array, function(obj){return JSON.stringify(obj)}).join(' ')
Update: To get the value properties
更新:获取值属性
var string = $.map(array, function(obj){
return obj.value
}).join(' ');
Demo: Fiddle
演示:小提琴
回答by Steven De Groote
Use Array.map
:
使用Array.map
:
let data = [
{
"animal": "cat",
"name": "Fluffy"
},
{
"animal": "dog",
"name": "Bowser"
},
{
"animal": "cat",
"name": "Felix"
}
]
Now extract the names using .map
:
现在使用.map
以下方法提取名称:
let names = data.map(item => item.name)
let nameString = names.join(' ')
And now nameString
contains Fluffy Bowser Felix
.
现在nameString
包含Fluffy Bowser Felix
.