2 回答
TA贡献1831条经验 获得超9个赞
好吧,它并不是那么优雅,但你可以像下面那样做。
var input = [{"mickey gray": 5}, {"mickey gray": 50}, {"mickey gray" : 500}, {"steve smith": 5}, {"steve smith": 50}, {"steve smith": 500}];
// basically - groupby key
var intermediate = input.reduce( (acc,i) => {
Object.keys(i).forEach( key => acc.hasOwnProperty(key) ? acc[key].push(i[key]) : acc[key] = [i[key]]);
return acc;
},{});
// take the key and last item from the values
var result = Object.entries(intermediate).map( entry => {
var [key,value] = entry;
return {[key]: value[value.length-1]};
});
console.log(result);
TA贡献1871条经验 获得超13个赞
向后循环可以完成这项工作,将用户名和最后索引存储在单独的字典中。您从右到左循环数组。如果用户不在字典中(即它是它的最后一个条目),则将其添加到字典中;否则它只会继续循环。
我建议以这种方式存储每个条目以使循环更容易:
{ userName: 'mickey gray',
value: 500 }
循环可能是这样的:
let indexDictionary = {};
for(let i = array.length - 1; i >= 0; i--) {
if(!indexDictionary[array[i].userName]) {
indexDictionary[array[i].userName] = array[i].value;
}
}
添加回答
举报
