Quiero crear un objeto de matriz a partir de la matriz plana que obtendré de los resultados de la consulta y quiero crear una estructura json como respuesta para pasarla como respuesta api. Por ejemplo, matriz plana
[{ user_id: '2311123', user_country: 'United States', user_city: 'ny', ssn: 229 }, { user_id: '451313', user_country: 'United States', user_city: 'abc', ssn: 147 }, { user_id: '65345', user_country: 'United States', user_city: 'abc', ssn: 444 }, { user_id: '763343', user_country: 'Australia', user_city: 'auus', ssn: 678 }]Quiero crear una estructura como- Salida esperada
{ "United States": [ { "ny": [ { "user_id": "2311123", "ssn": "7" } ] }, { "abc": [ { "user_id": "451313", "ssn": "147" }, { "user_id": "65345", "ssn": "444" } ] } ], "Australia": [ { "auus": [ { "user_id": "763343", "ssn": "678" } ] } ] }que tiene una matriz de objetos user_country y una matriz de objetos user_city asignadas. Probé este código, pero no pude lograr el resultado esperado:
const map = {}; results.forEach(arr => { console.log("arr",arr) if(map[arr.user_country]){ if(!map[arr.user_country].includes(arr.user_city)) map[arr.user_country].push(arr.user_city); }else{ map[arr.user_country] = [arr.user_city] } }); console.log(map);Esto podría producir los resultados esperados:
const array = [{ user_id: '2311123', user_country: 'United States', user_city: 'ny', ssn: 229 }, { user_id: '451313', user_country: 'United States', user_city: 'abc', ssn: 147 }, { user_id: '65345', user_country: 'United States', user_city: 'abc', ssn: 444 }, { user_id: '763343', user_country: 'Australia', user_city: 'auus', ssn: 678 }]; const map = array.reduce((map, {user_country, user_city, ...userInfo}) => { if (!map[user_country]) { map[user_country] = [{[user_city]: [{...userInfo}]}]; } else { const ex = map[user_country].find(city => Object.keys(city)[0] === user_city); if (!ex) { map[user_country].push({[user_city]: [{...userInfo}]}); } else { Object.values(ex)[0].push({...userInfo}); } } return map; }, {}); console.log(map);Por favor, compruebe esta solución:
const map = {}; results.forEach(arr => { const { user_country, user_id, user_city, ssn } = arr; if (!map[user_country]) { map[user_country] = []; } if (map[user_country][user_city]) { map[user_country][user_city].push({user_id, ssn}); } else { map[user_country][user_city] = [{user_id, ssn}]; } }); console.log(map) const results = [{ user_id: '2311123', user_country: 'United States', user_city: 'ny', ssn: 229 }, { user_id: '451313', user_country: 'United States', user_city: 'abc', ssn: 147 }, { user_id: '65345', user_country: 'United States', user_city: 'abc', ssn: 444 }, { user_id: '763343', user_country: 'Australia', user_city: 'auus', ssn: 678 } ] const out = {}; results.forEach(i => { out[i.user_country] = out[i.user_country] || {}; out[i.user_country][i.user_city] = out[i.user_country][i.user_city] || []; out[i.user_country][i.user_city].push({ user_id: i.user_id, ssn: i.ssn }) }) console.log(out)