Нужно модифицировать имеющийся объект
Существует объект:
let obj = '[{"departure city":"Moscow","entry_id":1},{"departure city":"Spb","entry_id":2},{"departure city":"Minsk","entry_id":3},{"departure city":"Spb","entry_id":4},{"departure city":"Moscow","entry_id":5}]';
console.log(JSON.parse(obj));
Я стремлюсь его привести к такому виду:
let obj = '[{"name":"Moscow","entries":[{"entry_id":1},{"entry_id":5}]},{"name":"Minsk","entries":[{"entry_id":3}]},{"name":"Spb","entries":[{"entry_id":2},{"entry_id":4}]}]';
console.log(JSON.parse(obj));
Мои попытка сделать это:
"use strict";
document.addEventListener("DOMContentLoaded", function() {
let cities = [];
let city1 = new Entry("Moscow", 1);
let city2 = new Entry("Spb", 2);
let city3 = new Entry("Minsk", 3);
let city4 = new Entry("Spb", 4);
let city5 = new Entry("Moscow", 5);
cities.push(city1, city2, city3, city4, city5);
//console.log(cities);
let res = cities.filter(filterByCity);
console.log(res);
});
function Entry(city, index) {
this["departure city"] = city;
this.entry_id = index;
}
function filterByCity(item) {
if (item["departure city"] === 'Spb') {
return true;
} else return false;
}
Максимум чего я добился, это вернуть массив с совпадающим городом, но дальше ступор. По идее следующий шаг это сделать cities.filter(filterByCity) в цикле, но тогда в функцию filterByCity надо как-то передавать slug города('Spb' or 'Moscow' etc.) Скорее всего что-то не то делаю. Подскажите, как можно исходный объект привести к нужному виду?
Ответы (2 шт):
Автор решения: Pavel Nazarian
→ Ссылка
let arr = [
{
"departure_city": "Moscow",
"entry_id": 1
},
{
"departure_city": "Spb",
"entry_id": 2
},
{
"departure_city": "Minsk",
"entry_id": 3
},
{
"departure_city": "Spb",
"entry_id": 4
},
{
"departure_city": "Moscow",
"entry_id": 5
}
]
let arr1 = arr.reduce((res,{departure_city,entry_id}) => {
let index = res.findIndex(el => el.name == departure_city);
if (index != -1){
res[index].entries.push({'entry_id':entry_id});
} else res.push({'name':departure_city,'entries':[{'entry_id':entry_id}]})
return res
},[])
console.log(arr1)
Автор решения: Sergey Glazirin
→ Ссылка
const arr = [{
"departure city": "Moscow",
"entry_id": 1
}, {
"departure city": "Spb",
"entry_id": 2
}, {
"departure city": "Minsk",
"entry_id": 3
}, {
"departure city": "Spb",
"entry_id": 4
}, {
"departure city": "Moscow",
"entry_id": 5
}];
function getCityEntries(array) {
const result = [];
const uniqueCities = getUniqueCities(array);
uniqueCities.forEach(item => {
result.push({
name: item,
entries: array.filter(city => city["departure city"] === item).map(city => ({
'entry_id': city.entry_id
}))
})
});
return result;
}
function getUniqueCities(array) {
return array.map(item => item["departure city"]).filter((v, i, a) => a.indexOf(v) === i);
}
console.log(getCityEntries(arr))