javascript 对对象数组中的值执行 .join
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16607557/
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
Perform .join on value in array of objects
提问by Hymanweirdy
If I have an array of strings, I can use the .join()
method to get a single string, with each element separated by commas, like so:
如果我有一个字符串数组,我可以使用该.join()
方法获取单个字符串,每个元素用逗号分隔,如下所示:
["Joe", "Kevin", "Peter"].join(", ") // => "Joe, Kevin, Peter"
I have an array of objects, and I'd like to perform a similar operation on a value held within it; so from
我有一个对象数组,我想对其中包含的值执行类似的操作;所以从
[
{name: "Joe", age: 22},
{name: "Kevin", age: 24},
{name: "Peter", age: 21}
]
perform the join
method only on the name
attribute, to achieve the same output as before.
join
仅对name
属性执行该方法,以实现与以前相同的输出。
Currently I have the following function:
目前我有以下功能:
function joinObj(a, attr){
var out = [];
for (var i = 0; i < a.length; i++){
out.push(a[i][attr]);
}
return out.join(", ");
}
There's nothing wrong with that code, it works, but all of a sudden I've gone from a simple, succinct line of code to a very imperative function. Is there a more succinct, ideally more functional way of writing this?
这段代码没有任何问题,它可以工作,但突然间我从一行简单、简洁的代码变成了一个非常命令式的函数。有没有更简洁、理想情况下更实用的写法?
回答by Benjamin Gruenbaum
If you want to map objects to something (in this case a property). I think Array.prototype.map
is what you're looking for if you want to code functionally.
如果您想将对象映射到某物(在本例中是一个属性)。Array.prototype.map
如果您想按功能进行编码,我认为这就是您要寻找的。
[
{name: "Joe", age: 22},
{name: "Kevin", age: 24},
{name: "Peter", age: 21}
].map(function(elem){
return elem.name;
}).join(",");
In modern JavaScript:
在现代 JavaScript 中:
[
{name: "Joe", age: 22},
{name: "Kevin", age: 24},
{name: "Peter", age: 21}
].map(e => e.name).join(",");
If you want to support older browsers, that are not ES5 compliantyou can shim it (there is a polyfill on the MDN page above). Another alternative would be to use underscorejs's pluck
method:
如果你想支持不兼容 ES5 的旧浏览器,你可以填充它(上面的 MDN 页面上有一个 polyfill)。另一种选择是使用 underscorejs 的pluck
方法:
var users = [
{name: "Joe", age: 22},
{name: "Kevin", age: 24},
{name: "Peter", age: 21}
];
var result = _.pluck(users,'name').join(",")
回答by basilikum
Well you can always override the toString
method of your objects:
那么你总是可以覆盖toString
你的对象的方法:
var arr = [
{name: "Joe", age: 22, toString: function(){return this.name;}},
{name: "Kevin", age: 24, toString: function(){return this.name;}},
{name: "Peter", age: 21, toString: function(){return this.name;}}
];
var result = arr.join(", ");
//result = "Joe, Kevin, Peter"
回答by Hymanweirdy
I've also come across using the reduce
method, this is what it looks like:
我也遇到过使用该reduce
方法,它是这样的:
[
{name: "Joe", age: 22},
{name: "Kevin", age: 24},
{name: "Peter", age: 21}
].reduce(function (a, b) {return (a.name || a) + ", " + b.name})
The (a.name || a)
is so the first element is treated correctly, but the rest (where a
is a string, and so a.name
is undefined) isn't treated as an object.
的(a.name || a)
是这样第一元件被正确地处理,但其余的(其中,a
是一个字符串,所以a.name
是未定义)不被视为一个对象。
Edit: I've now refactored it further to this:
编辑:我现在已经将它进一步重构为:
x.reduce(function(a, b) {return a + ["", ", "][+!!a.length] + b.name;}, "");
which I believe is cleaner as a
is always a string, b
is always an object (due to the use of the optional initialValue parameterin reduce
)
我相信这是吸尘器,a
始终是一个字符串,b
始终是一个对象(由于使用的可选参数初值中reduce
)
Edit 6 months later: Oh what was I thinking. "cleaner". I've angered the code Gods.
6 个月后编辑:哦,我在想什么。“清洁器”。我已经激怒了代码神。
回答by Ed Hinchliffe
I don't know if there's an easier way to do it without using an external library, but I personally loveunderscore.jswhich has tons of utilities for dealing with arrays, collections etc.
我不知道在不使用外部库的情况下是否有更简单的方法,但我个人喜欢underscore.js,它有大量用于处理数组、集合等的实用程序。
With underscore you could do this easily with one line of code:
使用下划线,您可以使用一行代码轻松完成此操作:
_.pluck(arr, 'name').join(', ')
_.pluck(arr, 'name').join(', ')
回答by ariel
On node or ES6+:
在节点或 ES6+ 上:
users.map(u => u.name).join(', ')
回答by C'estLaVie
lets say the objects array is referenced by the variable users
假设对象数组由变量引用 users
If ES6 can be used then the easiest solution will be:
如果可以使用 ES6,那么最简单的解决方案是:
users.map(user => user.name).join(', ');
If not, and lodashcan be used so :
_.map(users, function(user) {
return user.name;
}).join(', ');
回答by Davron Achilov
If object and dynamical keys: "applications\":{\"1\":\"Element1\",\"2\":\"Element2\"}
如果对象和动态键: "applications\":{\"1\":\"Element1\",\"2\":\"Element2\"}
Object.keys(myObject).map(function (key, index) {
return myObject[key]
}).join(', ')
回答by Jorge Aguilar
not sure, but all this answers tho they work but are not optiomal since the are performing two scans and you can perform this in a single scan. Even though O(2n) is considered O(n) is always better to have a true O(n).
不确定,但所有这些答案都有效但不是最优的,因为它们正在执行两次扫描,您可以在一次扫描中执行此操作。即使 O(2n) 被认为 O(n) 总是更好的有一个真正的 O(n)。
const Join = (arr, separator, prop) => {
let combined = '';
for (var i = 0; i < arr.length; i++) {
combined = `${combined}${arr[i][prop]}`;
if (i + 1 < arr.length)
combined = `${combined}${separator} `;
}
return combined;
}
This might look like old school, but allows me to do thig like this:
这可能看起来像老派,但允许我这样做:
skuCombined = Join(option.SKUs, ',', 'SkuNum');
回答by Nigelli
An old thread I know but still super relevant to anyone coming across this.
我知道一个旧线程,但仍然与遇到此问题的任何人都非常相关。
Array.map has been suggested here which is an awesome method that I use all the time. Array.reduce was also mentioned...
这里建议使用 Array.map,这是我一直使用的一种很棒的方法。还提到了 Array.reduce...
I would personally use an Array.reduce for this use case. Why? Despite the code being slightly less clean/clear. It is a much more efficient than piping the map function to a join.
对于这个用例,我个人会使用 Array.reduce。为什么?尽管代码稍微不那么干净/清晰。它比通过管道将 map 函数传递给连接更有效。
The reason for this is because Array.map has to loop over each element to return a new array with all of the names of the object in the array. Array.join then loops over the contents of array to perform the join.
这样做的原因是因为 Array.map 必须遍历每个元素以返回一个新数组,其中包含数组中对象的所有名称。Array.join 然后循环遍历数组的内容以执行连接。
You can improve the readability of Hymanweirdys reduce answer by using template literals to get the code on to a single line. "Supported in all modern browsers too"
您可以通过使用模板文字将代码放在一行中来提高 Hymanweirdys reduce answer 的可读性。“也支持所有现代浏览器”
// a one line answer to this question using modern JavaScript
x.reduce((a, b) => `${a.name || a}, ${b.name}`);
回答by haripds
try this
试试这个
var x= [
{name: "Joe", age: 22},
{name: "Kevin", age: 24},
{name: "Peter", age: 21}
]
function joinObj(a, attr) {
var out = [];
for (var i=0; i<a.length; i++) {
out.push(a[i][attr]);
}
return out.join(", ");
}
var z = joinObj(x,'name');
z > "Joe, Kevin, Peter"
var y = joinObj(x,'age');
y > "22, 24, 21"