[英]Manipulating Javascript array of objects
I have an array of objects and need to create a new array which contains the values of a specific key within the objects. 我有一个对象数组,需要创建一个新数组,其中包含对象中特定键的值。 Is there a more elegant way than the following code (note: without using anything more than JQuery).
是否有比以下代码更优雅的方式(注意:不使用任何东西比JQuery更多)。 Expected result is: 455, 387, 495
预期结果是:455,387,495
var arr=[{sid:387,rank:2},{sid:455,rank:1},{sid:364,rank:4},{sid:495,rank:3}];
var topThreeTemp = arr.filter(function(a){return a.rank<4;}).sort(function(a,b){return a.rank>b.rank;});
var topThreeSIDs=[];
for(var i=0;i<topThreeTemp.length;i++){
topThreeSIDs.push(topThreeTemp[i].sid);
}
console.log(topThreeSIDs.join(", "));
Use ES6 map
, instead of for
and ES6 arrow functions (syntax sugars): 使用ES6
map
,而不是for
和ES6箭头函数(语法糖):
const arr = [ { sid: 387,rank: 2 }, { sid: 455,rank: 1 }, { sid: 364,rank: 4 }, { sid: 495,rank: 3 } ] const topThreeSIDs = arr .filter(({ rank }) => rank < 4) .sort((a, b) => a.rank > b.rank) .map(({ sid }) => sid) console.log(topThreeSIDs.join(', '))
You could filter, sort with delta, slice and map sid
as result array. 您可以过滤,使用delta,slice和map
sid
作为结果数组进行排序。
var array = [{ sid: 387, rank: 2 }, { sid: 455, rank: 1 }, { sid: 364, rank: 4 }, { sid: 495, rank: 3 }], top3 = array .filter(({ rank }) => rank < 4) .sort((a, b) => a.rank - b.rank) .slice(0, 3) .map(({ sid }) => sid); console.log(top3.join(", "));
function pluck(objs, name, condition) {
var sol = [];
for (var i in objs) {
if (objs[i].hasOwnProperty(name) && condition && condition(objs[i])) {
// console.log(objs[i][name]);
sol.push(objs[i][name]);
}
}
return sol;
}
var arr = [{sid: 387, rank: 2}, {sid: 455, rank: 1}, {sid: 364, rank: 4}, {sid: 495, rank: 3}];
var pluckedArray = pluck(arr, sid, function (item) {
return item.rand < 4; // your custom condition
})
How about iterate the array only once, and build the resultant array? 怎么样只迭代一次数组,并构建结果数组?
arr.reduce((r, {rank, sid})=>(rank < 4 && (r[rank -1] = sid), r), [])
var arr = [{ sid: 387, rank: 2 }, { sid: 455, rank: 1 }, { sid: 364, rank: 4 }, { sid: 495, rank: 3 }], top3 = arr.reduce((r, {rank, sid})=>(rank < 4 && (r[rank -1] = sid), r), []); console.log(top3);
Note: When you need top 3 within highest rank 4
and also know ranks are unique, you can use this. 注意:当您需要最高等级
4
前三名并且也知道等级是唯一的时,您可以使用此。 If ranks are not unique you can use r.splice(rank-1, 0, sid)
instead of r[rank-1] = sid
and slice
top 3 at the end. 如果排名不是唯一的,您可以使用
r.splice(rank-1, 0, sid)
代替r[rank-1] = sid
并在末尾slice
top 3。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.