我有一组对象通过api调用来到我的Vuejs前端,我试图循环,删除重复项,然后返回一个具有唯一“阶段”的新数组及其相关的“id”。原始数组有几个我不需要的键/值。我也按阶段顺序对它们进行排序。这是我的代码:
salesPhases () {
let phases = this.$store.state.addresses.salesPhases
let uniquePhases = []
for (let i = 0; i < phases.length; i++) {
if (uniquePhases.indexOf(phases[i].phase_number) === -1) {
uniquePhases.push(phases[i].phase_number)
}
}
return uniquePhases.sort((a, b) => {
return a - b
})
}
以上代码适用于我需要的所有内容,包括id
。这是我尝试这样做,然后否定了独特的阶段条件。
uniquePhases.push([phases[i].phase_number, phases[i].id])
排序仍然有效,但它正在排序一个大的一维数组。阶段阵列看起来像这样:
{ "data": [
{
"id": "94e224af-135f-af31-3619-535acfae9930",
"street_address1": "407 48TH ST E",
"street_address2": null,
"phase": "101",
"sales_rep": "164",
"id": "abd90d6b-28a8-2be6-d6c1-abd9007aef38",
"name": "48TH ST E",
"block_minimum": 400,
"block_maximum": 498,
"side": 2
},
{
"id": "94e224af-135f-af31-3619-535acfae9930",
"street_address1": "407 48TH ST E",
"street_address2": null,
"phase": "101",
"sales_rep": "164",
"id": "abd90d6b-28a8-2be6-d6c1-abd9007aef38",
"name": "48TH ST E",
"block_minimum": 401,
"block_maximum": 499,
"side": 1
}
]
答案 0 :(得分:4)
您可以filter使用Set,然后将map项添加到仅包含id
和{{1 } {},然后是phase_number
的{{3}}:
phase_number
您还可以使用sort和reduce,然后将Map迭代器传播到数组
salesPhases () {
const uSet = new Set()
return this.$store.state.addresses.salesPhases
.filter(({ phase_number }) => uSet.has(phase_number) ? false : uSet.add(phase_number)) // get uniques by phase_number
.map(({ id, phase_number }) => ({ id, phase_number })) // get an object with the id and the phase_number
.sort((a, b) => a.phase_number - b.phase_number) // sort by phase_number
}
答案 1 :(得分:0)
一种解决方案是更新代码以推送整个阶段对象,而不仅仅是阶段编号,然后使用数组false
方法而不是find
来检查相位是否与给定号码。
试试这个:
indexOf
答案 2 :(得分:0)
我会利用lodash:https://lodash.com/docs#sortedUniqBy
salesPhases () {
return _.sortedUniqBy(this.$store.state.addresses.salesPhases,
phase => phase.phase_number)
}