gpt4 book ai didi

javascript - UnderscoreJS 对象组列表

转载 作者:行者123 更新时间:2023-12-02 16:49:57 25 4
gpt4 key购买 nike

我有一个来自数据库的对象数组,为了简洁起见,我想将其折叠。我已导入 underscore.js 来帮助完成此过程,但尝试使用提供的“groupBy”函数来压缩以下列表未成功:

[
{ID:2570,name:"jim",latitude:59.4,longitude:-7.29},
{ID:2573,name:"joe",latitude:54.4,longitude:-7.36},
{ID:2573,name:"joe",latitude:54.3,longitude:-7.37},
{ID:2574,name:"bob",latitude:58.4,longitude:-7.31},
{ID:2574,name:"bob",latitude:58.6,longitude:-7.38},
{ID:2574,name:"bob",latitude:58.8,longitude:-7.39},
{ID:2575,name:"mary",latitude:54.1,longitude:-7.30},
]

格式:

[
{ID:2570, name:"jim", locs : [[59.4,-7.29]]},
{ID:2573, name:"joe", locs : [[54.4,-7.36], [54.3,-7.37]]} //etc...
]

最佳答案

按照您的直觉使用_.groupBy

var data = [
{ID:2570,name:"jim",latitude:59.4,longitude:-7.29},
{ID:2573,name:"joe",latitude:54.4,longitude:-7.36},
{ID:2573,name:"joe",latitude:54.3,longitude:-7.37},
{ID:2574,name:"bob",latitude:58.4,longitude:-7.31},
{ID:2574,name:"bob",latitude:58.6,longitude:-7.38},
{ID:2574,name:"bob",latitude:58.8,longitude:-7.39},
{ID:2575,name:"mary",latitude:54.1,longitude:-7.30},
];

var groups = _.groupBy(data, function(locationObject) { return locationObject.ID; });

var result = _.map(groups, function(group) {
var condensed = {ID: group[0].ID, name: group[0].name};
condensed.locs = _.map(group, function(row) {
return [row.latitude, row.longitude];
});
return condensed;
});

document.getElementById('log').innerHTML = JSON.stringify(result, null, ' ');
<script src="http://underscorejs.org/underscore-min.js"></script>
<pre id="log"></pre>

关于javascript - UnderscoreJS 对象组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26758191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com